c# - Selecting a sub-list with an associated string value -
assume have following:
public class classa { public string description {get;set;} public list<product> products {get;set;} } public class classb { public string description {get;set;} public product singleproduct {get;set;} } public class classc { public list<classa> listofas {get;set;} public list<classb> breakdownlistofas() { // critical point } } at marked critical point, want return list of classb instances created examining listofas , decomposing such each instance of classb has single product , description classa instance in product resides.
example, if have:
var listofas = new list<classa> { new classa { description = "foo", products = new list<product> { p1, p2 } }, new classa { description = "bar", products = new list<product> { p3, p4 } } }; then return value of classc.breakdownlistofas() should match:
new list<classb> { new classb { description = "foo", product = p1 }, new classb { description = "foo", product = p2 }, new classb { description = "bar", product = p3 }, new classb { description = "bar", product = p4 }, } i know i'd use .selectmany() projecting sub-list, can't work out how achieve composition of projected sub-elements string parent object.
in linq method chain, this:
return listofas .selectmany(a => a.products, (a, p) => new classb { description = a.description, singleproduct = p }) .tolist(); the trick create object in result selector using both description classa instance , product classa's list.
Comments
Post a Comment