lambda expression C#从List中获取不匹配的记录 [英] lambda expression C# to get the unmatched record from a List

查看:80
本文介绍了lambda expression C#从List中获取不匹配的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我有一个list1 = {1,1,2,3,4,5}



我要比较列表中的项目。



我的代码:

var list2 = list1.GroupBy(c => c.action)。选择(g => g.FirstOrDefault())。ToList();



现在我有一个新的list2 = {1 ,1,2}

i想要从这个列表中获得2分。





或者如果是List = {1,1}

我想得到1分。



有什么建议吗?

Hi,

I have a list1 = {1,1,2,3,4,5}

I want to compare the items in the list.

My code:
var list2 = list1.GroupBy(c => c.action).Select(g => g.FirstOrDefault()).ToList();

Now i have a new list2 = {1,1,2}
i want to get a 2 out of this list.


or if List ={1,1}
I want to get 1 out of it.

Any suggestions, please?

推荐答案

你不需要lambda - 只需使用Linq方法:

You don''t need a lambda - just use Linq methods:
List<int> list1 = new int[] { 1, 1, 2, 3, 4, 5 }.ToList();
List<int> list2 = new int[] { 1, 1, 2 }.ToList();


var result = list1.Intersect(list2);
foreach (int i in result) Console.WriteLine(i);


int[] arr = new int[] { 1, 1, 2 };
//Create a dictionary where the key is each int occurance
//and the value is the number of int occurances.
Dictionary<int, int> dict = arr.Distinct().ToDictionary(i => i, i => arr.Where(ii=>ii==i).Count());
//now do what you like with it.. 
//eg get me the value that occurs least often, 
//which I think is what you're after:
int r=dict[dict.Values.Min()];





ATG



ATG


这篇关于lambda expression C#从List中获取不匹配的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆