0

I have the following situation:

I have a loop which could loop any amount of times. Within that loop I am calling a method which returns a List<CustomClass> After I have run through the loop I need to be able to compare all the List<CustomClass> items from each list and see which ones are common between all of them. In order to do this I have tried to put all the List<CustomClass> into another list: List<List<CustomClass> and then I need to use all of these to see which ones exist in all of them. I will be comparing on one property of my CustomClass (string Name)

This is what I have so far

public class CustomClass
{
    public string name;
}

public List<CustomClass> SomeMethod()
{
    List<List<CustomClass>> bigList = new List<List<CustomClass>>();
    List<CustomClass> finalList = new List<CustomClass>();
    for (int i=0;i<=5;i++)
    {            
        List<List<CustomClass>> newList = GetNewList();
        bigList.Add(newList);
    }
    //I now need to compare everything in bigList and create a new list with all common 
    //items in the list of bigList.
    return finalList ;
}

public List<CustomClass> GetNewList()
{
    List<CustomClass> newList = new List<CustomClass>();
    for (int i=0;i<=5;i++)
    {            
        CustomClass newClass = new CustomClass();
        newClass.name = "some name";
        newList.Add(newClass);
    }
    return newList;
{

I hope this makes sense. Any help on this is much appreciated.

Thanks

Edit

For example in List<List<CustomClass>> each List<CustomClass> contains a CustomClass with name set to "Pete", I then want to create a CustomClass with name set to "Pete" and add it to the final list.

Peuge
  • 1,461
  • 5
  • 20
  • 37

1 Answers1

4

see which ones are common between all of them

Use the Intersect extension method:

var common = list1.Intersect(list2);

Note that for this to work, you should either:

  • override Equals and GetHashCode in CustomClass
  • make CustomClass implement IEquatable<CustomClass>
  • provide Intersect with a custom comparer that implements IEqualityComparer<CustomClass>
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • Thanks for that, lead me on the right path. This person proabably asked it in a better way than I did :) http://stackoverflow.com/questions/1674742/intersection-of-multiple-lists-with-ienumerable-intersect – Peuge Apr 26 '11 at 09:21