如何比较两个List< T>? [英] How compare two List<T>?
本文介绍了如何比较两个List< T>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我上课
public class DB
{
public string 回答{获取; set ; }
public string question { get 跨度>; set ; }
public string url { get 跨度>; set ; }
}
列表< DB > list1 = new List < DB > ();
列表< 数据库 > list2 = new List < DB > ();
如何获取DB.answer不相似的所有列表元素?
解决方案
尝试类似list1.Except(list2.select(x => x.answer))。Union(list2.Except(list1.select(x =>) ; x.answer))
。
基本上这是基于原理,a.Except(b) .Union(b.Except(a)
建议将lista中的所有项目都不在listb中,然后将listb中的所有项目都不在lista中,然后在它们上面加上一个联合。
写一个简单的Comparer。然后使用
Union
并传入比较器public class DBComparer :IEqualityComparer< DB>
{
public bool Equals(DB x,DB y )
{
return x.answer == y.answer;
}
public int GetHashCode(DB db)
{
return db.answer.GetHashCode();
}
}
var filteredList = list1.Union(list2, new DBComparer())。ToList();
var result = list1.Where(a => list2.Any(b => a.answer!= b.answer))。ToList();
-KR
I have class
public class DB
{
public string answer{ get; set; }
public string question { get; set; }
public string url { get; set; }
}
List<DB> list1 = new List<DB>();
List<DB> list2 = new List<DB>();
How get all list elements, where DB.answer is not similar?
解决方案
Try something likelist1.Except(list2.select(x=>x.answer)).Union(list2.Except(list1.select(x=>x.answer))
.
Basically this is based on the princple,a.Except(b).Union(b.Except(a)
which suggests getting all items from lista not in listb and then all in listb not in lista and then putting a union on them.
Write a simple Comparer. Then use
Union
and pass in the comparerpublic class DBComparer : IEqualityComparer<DB> { public bool Equals(DB x, DB y) { return x.answer == y.answer; } public int GetHashCode(DB db) { return db.answer.GetHashCode(); } } var filteredList = list1.Union(list2,new DBComparer()).ToList();
var result = list1.Where(a => list2.Any(b => a.answer != b.answer)).ToList();
-KR
这篇关于如何比较两个List< T>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文