mahboub_mo
mahboub_mo

Reputation: 3038

get items from a list and it's inner list into one list?

i have a list

public class Org
{
  public string Name;
  public List<OrgPost> OrgPostCollection= new List<OrgPost>();
}

public class OrgPost
{
  public string OrgPostTitle;
}

and have:

List<Org> OrgCollection=//GetAll(Org);

and now i have a list of org like this

   [Name,OrgPostCollection]
   [Name2,OrgPostCollection2]
   ...

but i need something like this:

   [Name1,OrgPostCollection[0]]
   [Name1,OrgPostCollection[1]
   [Name2,OrgPostCollection[0]]
   [Name2,OrgPostCollection[1]]
   ...

Upvotes: 1

Views: 156

Answers (1)

Adam Houldsworth
Adam Houldsworth

Reputation: 64477

You can do a nested select:

   var flatEnumerable = from o in OrgCollection
                        from p in o.OrgPostCollection
                        select new Tuple<Org, OrgPost>(o, p);

You can then project whatever you want in the select, I project a Tuple<Org, OrgPost>.

The result flatEnumerable is IEnumerable<Tuple<Org, OrgPost>>, you can then call ToList or ToArray to resolve the enumerable into a list or array:

List<Tuple<Org, OrgPost>> flatList = flatEnumerable.ToList();
Tuple<Org, OrgPost>[] flatArray = flatEnumerable.ToArray();

Upvotes: 2

Related Questions