C#LINQ lambda - 获取比较两个列表中的字段的数据 [英] C#LINQ lambda -to get data comparing fields from two lists

查看:166
本文介绍了C#LINQ lambda - 获取比较两个列表中的字段的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个列表

ListOne ==> ID,名称,价值

ListTwo ==> ID,Desc,Value



ListOne的预期值

[1,A,200]

[1 ,A,300]

[1,A,520]

[2,B,300]

[2,B,350]

[2,B,400]

[3,C,40]

[3,C,20]



ListTwo-Master数据的价值

[1,模拟,500]

[2,福利,310]

[3,Chain,50]



我的要求

我想获得一份清单(比如ResultantList)只包含不超过ListTwo中相应ID值的值。



因此,ResultantList预计只有来自ListOne的以下数据
[1,A,520] ===>这里的值是520,520超过ListTwo中ID 1的值(500)

[2,B,350] ===>这里的值是350,350超过ListTwo中ID 2的值(310)

[2,B,400] ===>这里的值是400,400超过ListTwo中ID 2的值(310)

===> [...] ListOne中没有来自ID 3(名称为C)的值;因为ListOne中ID 3(名称C)的值(40,20)小于ListTwo中ID 3(Desc Chain)的值50



< b>我尝试了什么:



I have 2 Lists
ListOne ==> ID , Name, Value
ListTwo ==> ID, Desc, Value

Expected Values of ListOne
[1,A,200]
[1,A,300]
[1,A,520]
[2,B,300]
[2,B,350]
[2,B,400]
[3,C,40]
[3,C,20]

Values of ListTwo-Master Data
[1,Analog,500]
[2,Benefit,310]
[3,Chain,50]

My Requirement
I want to get a list(say ResultantList ) that will contain only the value that do not exceed the value of its corresponding ID in the ListTwo.

So the ResultantList is expected to have only the below data from ListOne
[1,A,520] ===> the value here is 520, 520 exceeds the value(500) of ID 1 in ListTwo
[2,B,350] ===> the value here is 350, 350 exceeds the value(310) of ID 2 in ListTwo
[2,B,400] ===> the value here is 400, 400 exceeds the value(310) of ID 2 in ListTwo
===>[...]There is no value from ID 3 (name as C) in ListOne ;as both values(40,20) having ID 3 (name C) in ListOne is less than the value 50 with ID 3 (Desc Chain) in ListTwo

What I have tried:

ResultantList = ListOne.Where(s => ListTwo.Any(l => (l.ID == s.ID && s.Value> l.Value))) .ToList();





但即使该值小于其对应值(wrt),也会获取所有值IDT)在ListTwo。



But this fetches all the values even if the value is less than its corresponding value (w.r.t ID) in ListTwo.

推荐答案

这里有两种不同的方法:



1.标准查询

Here are two different ways of doing it:

1. Standard Query
var resultantList = from item1 in list1
                    join item2 in list2
                    on item1.Id equals item2.Id
                    where item1.value < item2.value
                    select item1;





2. Lambda表达式



2. Lambda Expressions

var resultantList = list1.Where(item1 => 
                    list2.Any(item2 => item1.Id == item2.Id 
                            && item1.value < item2.value));





您可以在这里阅读更多内容: LINQ中的查询语法和方法语法(C#)| Microsoft Docs [ ^ ]


这篇关于C#LINQ lambda - 获取比较两个列表中的字段的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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