开发者

Comparing custom objects c#

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<C开发者_运维百科ustomClass>>();
    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.


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜