0

I have a List of ints. I need to select elements from a data source where a particular field/column matches each int in the list.

Data Source Example

ItemID  ListID
1       1
1       2
2       1

I want to find all Items that match all ListIDs from a List containing List IDs 1 and 2.

Currently I'm using...

List<Item> items = (from element in MyItems where listIDs.Contains(element.ListID) select element).ToList();

However, this produces an OR query and not an AND query across multiple rows for each distinct ItemID.

har07
  • 88,338
  • 12
  • 84
  • 137

5 Answers5

1

You can try this way :

List<Item> result = MyItems.GroupBy(o => o.ItemID)
                            //find group that contain all listIDs
                           .Where(o => !listIDs.Except(o.Select(x => x.ListID)).Any())
                           //flatten groups to items
                           .SelectMany(o => o)
                           .ToList();

Related question : Determine if a sequence contains all elements of another sequence using Linq

Community
  • 1
  • 1
har07
  • 88,338
  • 12
  • 84
  • 137
0

If you are trying to compare two list for equality, then you could use SequenceEqual method.

Something along the lines

list<item> results = (from element in MyItems where listIDs.SequenceEqauls(element.ListID) select element).ToList();

I am not entirely sure if I understood your question properly. When you say "particular field/column," is that field/column some kind of collection as well?

haku
  • 4,105
  • 7
  • 38
  • 63
0

if i got your question !! then try this

var MyItems=<your data column values>
var ItemsMatch=MyItems.Where(z=>MyIntsList.Contains(int.Pars(z.ToString()))).ToArray();
0

I'm not sure I understand the question. I think you have a list and you are trying to match rows that have both ListID & ItemID equal to ANY item in the list. If thats what you are sking this this is a way to do it:

List<Item> items = from element in MyItems
where listIDs.Contains(element.ListID) and listIDs.Contains(element.ItemID)

Or perhaps you are trying to match rows that have both ListID & ItemID equal to the SAME item in the list. If thats what you are sking this this is a way to do it:

List<Item> items = from element in MyItems
where listIDs.Contains(element.ListID) and element.ListID == element.ItemID
Mike Hixson
  • 5,071
  • 1
  • 19
  • 24
0

If i understood you correctly,this will do:

var result = (from item in MyItems
              from i in listIDs
              where i == item.ListId
              select item).ToList();

It will get all Item objects in MyItems list that have ListId present in ListId.

terrybozzio
  • 4,424
  • 1
  • 19
  • 25