Marky Ochoa
Marky Ochoa

Reputation: 23

C# Returning values from a list of classes

I have a class that's basically like this:

class myClass
{
    public string id;
    public string name;
}

If I have a List<myClass>, how can I get myClass.name when searching for it's corresponding myClass.id.

Upvotes: 0

Views: 69

Answers (3)

Kevin Nelson
Kevin Nelson

Reputation: 7663

I need a little more to go on...you should post some code where you are trying...otherwise you're going to get guess-answers...but anyway:

var list = new List<myClass>();
//add entries

var name = list.First( x => x.id == myId ).name;

If nulls are a potential, you can use FirstOrDefault and null conditional operator:

var name = list.FirstOrDefault( x => x.id == myId)?.name;

Upvotes: 1

Amit Kumar Singh
Amit Kumar Singh

Reputation: 4475

This is how you can do it.

Search your class list using where.

Get the FirstOrDefault() element.

If an element is found, First or Default returns it, otherwise it returns null. Check for null, if the element is not null, get the name.

void Main()
{
    List<myClass> classList = new List<myClass>();
    classList.Add(new myClass(){id="1", name="A"});
    classList.Add(new myClass(){id="2", name="B"});
    classList.Add(new myClass(){id="3", name="C"});
    classList.Add(new myClass(){id="4", name="D"});
    classList.Add(new myClass(){id="5", name="E"});

    var element = classList.Where(t=>t.id=="5").FirstOrDefault();
    if(element != null)
    {
      var name = element.name;
      Console.WriteLine(name);
    }
}

class myClass
{
    public string id;
    public string name;
}

Upvotes: 2

Tony Morris
Tony Morris

Reputation: 1007

LINQ extension methods can do this pretty simply.

var classes = new List<myClass>();
classes.AddRange(classesToAdd);

var foundClassName = classes.Single(x => x.id == idToSearchFor).name;

Upvotes: 1

Related Questions