dsi
dsi

Reputation: 3359

Need Linq expression to create list of string from dictionary of object (containing list)

Need linq expression to get list of distinct Iternary.Name from all dictionary entry's value's Iternary.Name.

Objects are below format:

public class IternaryInfo
{
   public string Name  { get; set; }   
   public Iternary[] IternaryList { get; set; }   
}

public class Iternary
{
   public string Name  { get; set; }   
}

Dictionary<String, IternaryInfo> dictionary = new Dictionary<String, IternaryInfo>();

Is this poss in one expression or have to go with looping.

tried - dictionary.Select(x=>x.Value.IternaryList).ToList(), but not sure, how to pick -Name field from Iternary.

Upvotes: 1

Views: 70

Answers (1)

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43886

You need to:

  • flatten the lists using SelectMany and then
  • project the Iternarys to their Names using Select and then
  • use Distinct to get only distinct values

    var result = dictionary.Values
                       .SelectMany(v => v.IternaryList)
                       .Select(i => i.Name)
                       .Distinct().ToList();
    

Upvotes: 7

Related Questions