ZoneArisK
ZoneArisK

Reputation: 15

fill a list with a parameter in an object list c#

Good morning, I'm looking for a more efficient way to fill a list of any type with an object parameter.

Example (my class) :

public class Thème
{
    public string Thème_ { get; set; }
    public Liste[] Listes { get; set; }
}

My code that I currently have to do what I want to do:

        List<string> nomDesThèmesDisponible = new List<string>();

        foreach(Thème thème in Data.Thèmes)
        {
            nomDesThèmesDisponible.Add(thème.Thème_);
        }

I think there's an easier way to do that (with linq?).

Thank you for offering me your solutions

Upvotes: 0

Views: 211

Answers (2)

Jasper Kent
Jasper Kent

Reputation: 3676

List<string> nomDesThèmesDisponible = Data.Thèmes.Select (t => t.Thème_).ToList();

Upvotes: 0

Daniel A. White
Daniel A. White

Reputation: 190945

You can do

nomDesThèmesDisponible.AddRange(Data.Thèmes.Select(t => t.Thème_));

or

nomDesThèmesDisponible = Data.Thèmes.Select(t => t.Thème_).ToList();

These ways not anymore efficient, just more concise.

Upvotes: 2

Related Questions