LINQ filter LIST values

Viewed 196

I have LINQ query

Label = c.Name.Translations.Select(label => new Label
                {                        
                    Rus = label.Text,
                    Eng = label.Text,
                }),

Translation class

public int Id { get; set; }

public string Text { get; set; }

public virtual ICollection<Translation> Translations { get; set; }



  public class Translation
    {
        public int Id { get; set; }
        public string Language { get; set; }
        public string Text { get; set; }
    }

which return list like this

{
"rus":"Нью-Йорк",
"eng":"Нью-Йорк"
},
{
"rus":"New-York",
"eng":"New-York"

My goal is have one item like this

"rus":"Нью-Йорк",
"eng":"New-York"

How can i filter it ?

4 Answers

This should do the job:

var labels = new Dictionary<string, string>();
foreach(var item in c.Name.Translations)
{
    labels.add(item.Language, item.Text);
}

Edit

var labels = c.Name.Translations.ToDictionary(t => t.Language, t => t.Text);
var label = c.Name.Translations.ToDictionary(translation => translation.Language, translation => translation.Text);

This creates a dictionary which can be accessed in the following way

label["eng"] // This returns "New York"

You can achieve this by a LINQ query for each of your Label class property:

var resultLabel = new Label
{
    Eng = Translations.FirstOrDefault(trans => trans.Language == "English")?.Text,
    Rus = Translations.FirstOrDefault(trans => trans.Language == "Russian")?.Text,
};

You can do something like this:

Dictionary<string, string> langText = new Dictionary<string, string>();
c.Name.Translations.ForEach(x => langText.Add(x.Language, x.Text));

langText will contain your data.

Related