如何找出两个列表的差异<;对象>;在c#中使用lambda表达式
我有两个链接类型列表如何找出两个列表的差异<;对象>;在c#中使用lambda表达式,c#,linq,C#,Linq,我有两个链接类型列表 Link { Title; url; } 我有两个链表(链表lst1和链表lst2) 现在我想要的元素不是在lst1中,而是在lst2中 如何使用lambda表达式实现这一点。 我不想用for循环 class CompareLists { static void Main() { // Create the IEnumerable data sources. string[] names1
Link
{
Title;
url;
}
我有两个链表(链表lst1和链表lst2)
现在我想要的元素不是在lst1中,而是在lst2中
如何使用lambda表达式实现这一点。
我不想用for循环
class CompareLists
{
static void Main()
{
// Create the IEnumerable data sources.
string[] names1 = System.IO.File.ReadAllLines(@"../../../names1.txt");
string[] names2 = System.IO.File.ReadAllLines(@"../../../names2.txt");
// Create the query. Note that method syntax must be used here.
IEnumerable<string> differenceQuery =
names1.Except(names2);
// Execute the query.
Console.WriteLine("The following lines are in names1.txt but not names2.txt");
foreach (string s in differenceQuery)
Console.WriteLine(s);
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
}
/* Output:
The following lines are in names1.txt but not names2.txt
Potra, Cristina
Noriega, Fabricio
Aw, Kam Foo
Toyoshima, Tim
Guy, Wey Yuan
Garcia, Debra
*/
如果您需要表达一种自定义的平等思想,例如通过ID,则需要实现IEqualityComparer。例如:
public class IdComparer : IEqualityComparer<CustomObject>
{
public int GetHashCode(CustomObject co)
{
if (co == null)
{
return 0;
}
return co.Id.GetHashCode();
}
public bool Equals(CustomObject x1, CustomObject x2)
{
if (object.ReferenceEquals(x1, x2))
{
return true;
}
if (object.ReferenceEquals(x1, null) ||
object.ReferenceEquals(x2, null))
{
return false;
}
return x1.Id == x2.Id;
}
}
编辑:如注释中所述,这将删除任何重复的元素;如果您需要保留重复的元素,请告诉我们……从列表2中创建一个集合并使用以下内容可能是最简单的:
var list3=list1.Where(x=>!set2.Contains(x)).ToList()
参考比较:
list2.Except(list1);
对于值比较,您可以使用:
list2.Where(el2 => !list1.Any(el1 => el1.Title == el2.Title && el1.url == el2.url));
在集合操作中,您要查找的是 减去交集的并集 所以 (列表1联合列表2)除(列表1交叉列表2) 查看此链接了解linq集合操作
你能发布一些你尝试过的代码吗?我想要值比较见:Enumerable.Exception method!
List1.Exception(List2);
我想说这个答案看起来像是的副本。为什么不指向那个答案呢?@JoelWahlund看到最后一行这对我来说就像魅力一样。非常感谢:)
list2.Except(list1);
list2.Where(el2 => !list1.Any(el1 => el1.Title == el2.Title && el1.url == el2.url));