比较自定义对象C# [英] Comparing custom objects 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
中的Equals
和GetHashCode
- 使
CustomClass
实现IEquatable<CustomClass>
- 通过实现
IEqualityComparer<CustomClass>
的自定义比较器为
Intersect
提供
- override
Equals
andGetHashCode
inCustomClass
- make
CustomClass
implementIEquatable<CustomClass>
- provide
Intersect
with a custom comparer that implementsIEqualityComparer<CustomClass>
这篇关于比较自定义对象C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!