Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LINQ to populate a collection from a property that has n elements

Tags:

c#

linq

I have the following class:

public class A
{
   public List<object> MyItems { get; set; }
   public Color Color { get; set; }
   public object MyItem { get set; }
}

Each instance of A can have n MyItems.

Given a list of A's, I need to filter them by color, and create a new list, in which a new instance of A is created for every element of the MyItems collection.

List<A> Aitems = originalItems.Where(b => b.color == color)
                              .Select(b=>
{
    A aItem = b;
    // Problem below. Is there a way to create more
    // aItems for every object in MyItems collection?
    b.MyItem = b.MyItems[0];
    return aItem;
}).ToList();

Is there a way to create more aItems for every object in MyItems collection using LINQ or should I use a standard foreach?

like image 392
laconicdev Avatar asked Dec 04 '25 18:12

laconicdev


1 Answers

Are you looking for something like this?

var query = from b in originalItems
            where b.Color == color
            from item in b.MyItems
            select new A
            {
                MyItems = b.MyItems,
                Color = b.Color,
                MyItem = item,
            };

var result = query.ToList();
like image 179
dtb Avatar answered Dec 06 '25 08:12

dtb