在C#的列表中获取通用元素 [英] get common elements in lists in C#
本文介绍了在C#的列表中获取通用元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个排序列表,如下所示:
I have two sorted lists as below:
var list1 = new List<int>() { 1, 1, 1, 2, 3 };
var list2 = new List<int>() { 1, 1, 2, 2, 4 };
我希望输出为:{1, 1, 2}
如何在C#中执行此操作? 有没有使用Linq的方法?
How to do this in C#? Is there a way using Linq?
推荐答案
多余的1表示您不能使用Intersect
,因为它会返回一个集合.
The extra 1 means you can't use Intersect
because it returns a set.
以下代码可以满足您的需求:
Here's some code that does what you need:
var list1 = new List<int>() { 1, 1, 1, 2, 3 };
var list2 = new List<int>() { 1, 1, 2, 2, 4 };
var grouped1 =
from n in list1
group n by n
into g
select new {g.Key, Count = g.Count()};
var grouped2 =
from n in list2
group n by n
into g
select new {g.Key, Count = g.Count()};
var joined =
from b in grouped2
join a in grouped1 on b.Key equals a.Key
select new {b.Key, Count = Math.Min(b.Count, a.Count)};
var result = joined.SelectMany(a => Enumerable.Repeat(a.Key, a.Count));
CollectionAssert.AreEquivalent(new[] {1, 1, 2}, result);
这篇关于在C#的列表中获取通用元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文