在两个linq语句中合并并删除重复项 [英] union in two linq statements and remove the duplicate
问题描述
我已经在互联网上搜索了一段时间,但找不到我真正需要的东西.我的问题是我有两个linq语句,我计划将它们放在UNION中,以便将它们合并到1个单一的列表集中,但是我想删除这些重复的值.具体而言,这是一个场景:
I have been searching for a while in the internet yet cant find what i really needed. My problem is that I have two linq statements which I am planning to have them in UNION so that they'll be mergen into 1 single set of list but I want to removed those duplicate values. To be specific here is the a scenario:
query 1 = "this is a test","Yes", "This is a remark"
"this is a test2","No", "This is the second remark"
query 2 = "this is a test","",""
"this is a test2","",""
"this is a test3","",""
"this is a test4","",""
现在我想发生的事情是这样的:
now what I want to happen is something like this:
"this is a test","Yes", "This is a remark"
"this is a test2","No", "This is the second remark",
"this is a test3","",""
"this is a test4","",""
我该如何在LINQ中做到这一点?谢谢!!
How can I do this in LINQ?thanks in advance!
推荐答案
您可以使用以下查询:
var result = from item in query2
let match = query1.SingleOrDefault (e => e[0] == item[0])
select match ?? item;
这将遍历query2
,对于每个项目,它使用SingleOrDefault
在query1
中找到与项目的第一个元素匹配的项目,即null
.然后select
会从query1
生成一个名为match的项目(如果不是null
的话),或者是当前的query2
项.
This will iterate over query2
, and for each item it uses SingleOrDefault
to find the item in query1
where the first elements of the items match, or null
. Then the select
yields either the item called match from query1
, if it is not null
, or the current item of query2
.
另一种可能更快的方法是创建一个合适的IEqualityComparer
并使用Union
,如下所示:
Another, probably faster approach is to create an appropriate IEqualityComparer
and using Union
, like this:
class FirstElementComparer : IEqualityComparer<string[]>
{
//TODO error checking
public bool Equals(string[] a, string[] b)
{
return a[0].Equals(b[0]);
}
public Int32 GetHashCode(string[] obj)
{
return obj[0].GetHashCode();
}
}
并像这样使用它:
void Main()
{
string[][] query1 = {new [] {"this is a test","Yes", "This is a remark"},
new [] {"this is a test2","No", "This is the second remark"}};
string[][] query2 = {new [] {"this is a test","",""},
new [] {"this is a test2","",""},
new [] {"this is a test3","",""},
new [] {"this is a test4","",""}};
query1.Union(query2, new FirstElementComparer()).Dump();
}
Union
使用EqualityComparer
将query1
中的元素与query2
中的元素进行比较.只需比较每个数组中的第一项即可.
The EqualityComparer
is used by Union
to compare the elements in query1
with the elements in query2
. It does so by just comparing the first item in each array.
结果:
这篇关于在两个linq语句中合并并删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!