List<int> lst1 = new List<int>{1,2,3,5,2};
List<int> lst2 = new List<int>{4,5,6,1,6};
List<int> lst3 = new List<int>();
预期输出: lst3 = {1,2,3,4,5,6}使用LINQ从两个列表中选择不同的元素?
谁能帮助我的LINQ代码从两个列表中选择不同的元素?
谢谢
List<int> lst1 = new List<int>{1,2,3,5,2};
List<int> lst2 = new List<int>{4,5,6,1,6};
List<int> lst3 = new List<int>();
预期输出: lst3 = {1,2,3,4,5,6}使用LINQ从两个列表中选择不同的元素?
谁能帮助我的LINQ代码从两个列表中选择不同的元素?
谢谢
基本上,你可以做
lst1.AddRange(lst2);
List<int> lst3 = lst1.Distinct().ToList();
使用Union()
方法,产生两个列表的并集,返回一个包含所有存在于这两个项目一个新的列表清单:
lst3 = list1.Union(lst2).OrderBy(p=>p).ToList();
基本方法
List<int> lst3 = new List<int>();
foreach (int x in lst1)
if (!lst3.Contains(x))
lst3.Add(x);
foreach (int x in lst2)
if (!lst3.Contains(x))
lst3.Add(x);
由于OP要求提供LINQ解决方案,因此您的答案可能因为投票而被否决。 – gldraphael 2014-10-05 11:18:05
另一种方法(我认为最effcient一个[摊销]):
var hashSet = new HashSet<int>(lst1);
foreach (var item in lst2)
{
hashSet.Add(item);
}
var lst3 = hashSet.ToList();
LINQ:
var lst3 = lst1.Union(lst2).ToList();
'联盟'已经删除了重复,不需要'独特' – Magnus 2014-10-05 11:18:31
@Magnus是的,你是对的,我错过了。 – 2014-10-05 11:19:49
您可以使用UNION和ResultSet中取不同值
lst3 = lst1.Union(lst2).Distinct().ToList();
您现在正在使用哪些代码,以及您获得了哪些输出?在请求我们为您工作之前向我们展示您已经尝试了些什么。 – 2014-10-05 10:59:37
我不知道该怎么做。我只是C#的新手。我曾尝试使用连接。 这是我做的 var z =从x in n join y in m on true等于true select(x); – 2014-10-05 11:03:32