Denis Denis - 2 months ago 5
C# Question

How to join a list member and indicative member to create list of indicative and list member

Suppose I have classes like:

public class LabeledStock {
public Stock StockInfo { get; set; }
public IList<Label> Labels { get; set; }
}

public class StockLabel {
public Stock StockInfo {get; set; }
public Label Label {get; set; }
}


I am struggling to find the correct way to write a Linq expression that converts a list of
LabeledStock
objects to a list of
StockLabel
objects (i.e. flattening the Labels property but keeping it together with the stock object)

Answer

Using SelectMany extension method:

var result= labeledStockList.SelectMany(e=>e.Labels.Select(l=>new StockLabel{StockInfo=e.StockInfo,Label=l}));
Comments