Reputation: 3315
I'm trying to do something I'm not sure LINQ can do -but let's try! I have 2 classes; one is a list structure for the other:
public class1 {
public int id {get; set;}
public string title {get; set;}
public List<class2> subcat {get; set;}
}
public class2 {
public int Value {get; set;}
public string Text {get; set;}
}
Is it possible to fill such structure with LINQ? Something like:
return (from r in results
from sub in subresults.Where(sub => sub.id == r.subid).DefaultIfEmpty()
select new class1 {
id = r.id,
title = r.title,
subcat = [GET TWO COLUMNS FROM 'SUB' INTO THIS]
}).ToList()
Is this possible? I'd hate to have to build them manually by using nested loops, etc.
Thanks in advance!
Upvotes: 2
Views: 1952
Reputation: 109165
You can use a navigation property to load results and subresults in one query.
from r in results
select new class1 {
id = r.id,
title = r.title,
subcat = r.Subresults.Select(sr =>
new class2 { Value = sr.Value, Text = sr.Text })
...assuming that the navigation property result.Subresults
exists or otherwise can be created for convenience.
AutoMapper could also be useful here. If yo define two mappings (result => class1
, subresult => class2
) it will load the nested collection automatically.
Upvotes: 0
Reputation: 3269
Is this what you need?
return (from r in results
select new class1 {
id = r.id,
title = r.title,
subcat = (from sub in subresults
where sub.id == r.subid
select new class2 { Value = sub.Value, Text = sub.Text }).ToList()
}).ToList()
Upvotes: 4