Click here to Skip to main content
15,900,511 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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:

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


But this fetches all the values even if the value is less than its corresponding value (w.r.t ID) in ListTwo.
Posted
Updated 20-Aug-17 13:00pm
v2
Comments
jeAntoni 22-Aug-17 13:52pm    
This works fine. Somehow I had missed an assignment in between, and thus was seeing the right output.

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

1 solution

Here are two different ways of doing it:

1. Standard Query
C#
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 Expressions
C#
var resultantList = list1.Where(item1 => 
                    list2.Any(item2 => item1.Id == item2.Id 
                            && item1.value < item2.value));


You can read more here: Query Syntax and Method Syntax in LINQ (C#) | Microsoft Docs[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900