比较自定义对象C# [英] Comparing custom objects c#

查看:185
本文介绍了比较自定义对象C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情况:

我有一个循环,可以循环任意次.在该循环中,我正在调用一个返回List<CustomClass>的方法,在循环中运行后,我需要能够比较每个列表中的所有List<CustomClass>项,并查看它们之间共有哪些项.为了做到这一点,我尝试将所有List<CustomClass>放入另一个列表:List<List<CustomClass>,然后我需要使用所有这些内容来查看所有这些内容中都存在哪些.我将比较CustomClass(字符串名称)的一个属性

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.

谢谢

修改

例如,在List<List<CustomClass>>中,每个List<CustomClass>都包含一个名称设置为"Pete"的CustomClass,然后我想创建一个名称设置为"Pete"的CustomClass,并将其添加到最终列表中.

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

使用Intersect扩展方法:

var common = list1.Intersect(list2);

请注意,要执行此操作,您应该:

Note that for this to work, you should either:

  • 覆盖CustomClass中的EqualsGetHashCode
  • 使CustomClass实现IEquatable<CustomClass>
  • 通过实现IEqualityComparer<CustomClass>
  • 的自定义比较器为Intersect提供
  • override Equals and GetHashCode in CustomClass
  • make CustomClass implement IEquatable<CustomClass>
  • provide Intersect with a custom comparer that implements IEqualityComparer<CustomClass>

这篇关于比较自定义对象C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆