当前位置: 首页 > 编程语言 > C#

在C#中获取列表中的公共元素

时间:2023-04-10 14:18:41 C#

在C#中获取列表中的公共元素我有两个排序列表,如下所示:varlist1=newList(){1,1,1,2,3};varlist2=newList(){1,1,2,2,4};我希望输出为:{1,1,2}我如何在C#中执行此操作?有没有办法使用Linq来做到这一点?额外的1意味着您不能使用Intersect,因为它返回一个集合。这里有一些代码可以做你想做的事:varlist1=newList(){1,1,1,2,3};varlist2=newList(){1,1,2,2,4};vargrouped1=fromninlist1groupnbynintogselectnew{g.Key,Count=g.Count()};vargrouped2=fromninlist2groupnbynintogselectnew{g.Key,Count=g.Count()};varjoined=frombingrouped2joinaingrouped1onb.Keyequalsa.Keyselectnew{b.Key,Count=Math.Min(b.Count,a.Count)};varresult=joined.SelectMany(a=>Enumerable.Repeat(a.Key,a.Count));CollectionAssert.AreEquivalent(new[]{1,1,2},结果);使用相交:varcommonElements=list1.Intersect(list2).ToList();这很好用:varlist1=newList(){1,1,1,2,3};varlist2=newList(){1,1,2,2,4};varlookup1=list1.ToLookup(x=>x);varlookup2=list2.ToLookup(x=>x);varresults=lookup1.SelectMany(l1s=>lookup2[l1s.Key].Zip(l1s,(l2,l1)=>l1));我很晚才回答这个问题,这可能对未来的访客有所帮助。以上就是C#学习教程:获取C#中列表中公共元素共享的所有内容。如果对大家有用,需要进一步了解C#学习教程,希望大家多多关注——Listp=newList{1,1,1,2,3};列表q=新列表{1,1,2,2,4};列表x=新列表();for(inti=0;i本文搜集自网络,不代表立场,如涉及侵权,请点击右边联系管理员删除。如需转载请注明出处: