Reputation: 839
I have a series of type List<Int32>
and another series of List<ClassA>
, where ClassA
has the following representation :
public ClassA
{
public String PropertyA {get; set;}
public List<Int32> PropertyB {get; set;}
public String PropertyC {get; set;}
}
I want to retrieve using LINQ a series of type List<KeyValuePair<PropertyC, Int32>>
where Int32
is contained within List<Int32>
PropertyB
.
Can this be done using one linq statement?
Upvotes: 0
Views: 166
Reputation: 16038
var q = (from i in listOfInts
from a in listOfA
where
a.PropertyB.Contains(i)
select new KeyValuePair<String, int>(a.PropertyC, i))
.ToList();
Upvotes: 1
Reputation: 5725
var idList = GetIdList(); //List of integer
var objectList = GetObjectList(); //List of ClassA
var pairs = objectList
.SelectMany(item => item.PropertyB
.Select(id => new KeyValuePair<string, int>(item.PropertyC, id)))
.Where(item => idList.Contains(item.Value));
Upvotes: 0
Reputation: 31606
Not completely sure what you mean by "where Int32 is contained within List<Int32> PropertyB
". I'm interpreting it to mean that you want the value part of the KeyValuePair to be some integer that's in PropertyB. In the example below I pick the first one.
List<ClassA> myList = GetListOfStuff(); //However you get the list
var results = from myList
select new KeyValuePair<string, int>(a.PropertyC, a.PropertyB.First());
Upvotes: 0
Reputation: 1503290
I think you're looking for something like:
var query = (from x in listOfInt32s
from y in listOfClassAs
where y.PropertyB.Contains(x)
select new KeyValuePair<string, int>(y.PropertyC, x))
.ToList();
... but I'm not entirely sure.
(As per the comments, I've changed the first KeyValuePair
type argument to string
.)
Upvotes: 2