Linq select one id with flattened list (example)

If you have an object with an id property and another property with a list of objects (has inheritance) and wants to get a new list with the inherited list flattened and keep the id. You can do like this:

public class Test
{
private void TestMethod()
{

Category _cat1 = new Category();
_cat1.Color = "Blue";

Category _cat2 = new Category();
_cat2.Color = "Green";

Category _cat3 = new Category();
_cat3.Color = "Red";

Category _cat4 = new Category();
_cat4.Color = "Yellow";

Category _cat5 = new Category();
_cat5.Color = "Lime";

List list1 = new List();
list1.Add(_cat1);
list1.Add(_cat2);
list1.Add(_cat3);

List list2 = new List();
list2.Add(_cat4);
list2.Add(_cat5);

List _listCar = new List();
_listCar.Add(new Car() { Id = 1, Categories = list1 });
_listCar.Add(new Car() { Id = 2, Categories = list2 });

var item = (from x in _listCar
.SelectMany(x => x.Categories, (Ids, Cars) =>
new { Ids, Cars })
select new
{
Id = x.Ids.Id,
Cat = x.Cars.Color
}).ToList();

var aba = item;

}
}
public class Car
{
public int Id { get; set; }
public List Categories { get; set; }

}
public class Category
{
public string Color { get; set; }
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.