Home > Mobile >  How find all the items of a list which are not in a generic list with multiple condition
How find all the items of a list which are not in a generic list with multiple condition

Time:02-27

I have a list "A" and a generic list "B". I need to find all the items of "A" those are not in "B" with multiple condition.

List "A":

EXWORK
CENTAGES
PREMIUM

List "B":

PARTICULARS   CATAGORY   DETAIL
EXWORK        ERECTION     ABC
CENTAGES      ERECTION     ABC
PREMIUM       SUPPLY       ABC

For this I use following code:

var value = A.Where(a => B.All(b => b.CATAGORY == "SUPPLY" && b.PARTICULARS!=a));

but this return the value "Premium" also whereas it shouldn't be. I am not figuring out where I am making mistake.

My Desired result is:

EXWORK
CENTAGES

CodePudding user response:

I think perhaps you mean:

var value = A.Where(a => !B.Any(b => b.CATAGORY == "SUPPLY" && b.PARTICULARS == a));

CodePudding user response:

If you look at your query, you are trying to filter list A based on the condition from List B i.e b.CATAGORY == "SUPPLY" and PARTICULARS should be present in A list.

To get desire output, you have iterate though List B and filter records based on condition b.CATAGORY == "SUPPLY" and PARTICULARS property,

var result = B
    .Where(x => x.CATAGORY == "ERECTION" && A.Contains(x.PARTICULARS))  //Use Contains.
    .Select(x => x.PARTICULARS);  //Select only PARTICULARS value.

Try Online


If you want data from List A, then you can break your linq in two steps,

var resultB = B
    .Where(x => x.CATAGORY == "SUPPLY")
    .Select(x => x.PARTICULARS).ToList();

var value = A.Except(resultB);

CodePudding user response:

Do you need to find all items in A that are not listed as a PARTICULAR categorized as SUPPLY in B?

If so, you could find all items in B where CATEGORY = "SUPPLY" and return list A except the PARTICULAR values of the filtered B items.

var value = A.Except(
    B.Where(b => b.CATAGORY == "SUPPLY")
        .Select(b => b.PARTICULARS));

Example fiddle here.

  • Related