Robert Robert - 1 year ago 110
C# Question

How can I find a specific element in a List<T>?

My application uses a list like this:

List<MyClass> list = new List<MyClass>();

Using the
method, another instance of
is added to the list.

provides a.o. the following methods:

public void SetId(String Id);
public String GetId();

How can I find a specific instance of
by means of using the
method? I know there is the
method but I don't know if this would work here?!

Answer Source

Use a lambda expression

MyClass result = list.Find(x => x.GetId() == "xy");

Note: C# has a built-in syntax for properties. Instead of writing Set- and Get-methods, write

private string _id;
public string Id
        return _id;
        _id = value;

value is a contextual keyword known only in the set accessor. It represents the value assigned to the property.

Since this pattern is often used, C# provides automatically implemented properties. They are a short version of the code above; however, the backing variable is hidden and not accessible (it is accessible from within the class in VB, however).

public string Id { get; set; }

You can simply use them like this (as if you were accessing a field)

var obj = new MyClass();
obj.Id = "xy";       // Calls the setter with "xy" assigned to the value parameter.
string id = obj.Id;  // Calls the getter.

Using properties, you would search for items in the list like this

MyClass result = list.Find(x => x.Id == "xy"); 

You can also use automatically implemented properties if you need a read-only property:

public string Id { get; private set; }

This enables you to set the Id within the class but not from outside. If you need to set it in derived classes as well you can also protect the setter

public string Id { get; protected set; }

And finally, you can declare properties as virtual and override them in deriving classes, allowing you to provide different implementations for getters and setters; just as for ordinary virtual methods.

Since C# 6.0 (Visual Studio 2015, Roslyn) you can write getter-only auto-properties with an inline initializer

public string Id { get; } = "A07"; // Evaluated once when object is initialized.

You can also initialize getter-only properties within the constructor instead.

Beginning with C# 6.0 you can also write properties as expression-bodied members

public DateTime Yesterday => DateTime.Date.AddDays(-1); // Evaluated at each call.
// Instead of
public DateTime Yesterday { get { return DateTime.Date.AddDays(-1); } }

See: .NET Compiler Platform ("Roslyn")
         New Language Features in C# 6

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download