Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ filter LIST values

Tags:

c#

.net

linq

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 ?

like image 368
NeoXX Avatar asked Nov 17 '25 09:11

NeoXX


2 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);
like image 168
Siavash Rostami Avatar answered Nov 20 '25 00:11

Siavash Rostami


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"
like image 22
Nielsw Avatar answered Nov 19 '25 23:11

Nielsw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!