145

My application uses a list like this:

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

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

MyClass provides, among others, the following methods:

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

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Robert Strauch
  • 12,055
  • 24
  • 120
  • 192

8 Answers8

335

Use a lambda expression

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

Note: C# has a built-in syntax for properties. Instead of writing getter and setter as ordinary methods (as you might be used to from Java), write

private string _id;
public string Id
{
    get
    {
        return _id;
    }
    set
    {
        _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 auto-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 properties 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 auto-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. Getter-only auto-properties are true read-only properties, unlike auto-implemented properties with a private setter.

This works also with read-write auto-properties:

public string Id { get; set; } = "A07";

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

Starting with C# 7.0, both, getter and setter, can be written with expression bodies:

public string Name
{
    get => _name;                                // getter
    set => _name = value;                        // setter
}

Note that in this case the setter must be an expression. It cannot be a statement. The example above works, because in C# an assignment can be used as an expression or as a statement. The value of an assignment expression is the assigned value where the assignment itself is a side effect. This allows you to assign a value to more than one variable at once: x = y = z = 0 is equivalent to x = (y = (z = 0)) and has the same effect as the statements z = 0; y = 0; x = 0;.

Since C# 9.0 you can use read-only (or better initialize-once) properties that you can initialize in an object initializer. This is currently not possible with getter-only properties.

public string Name { get; init; }

var c = new C { Name = "c-sharp" };

Beginning with C# 11, you can have a required property to force client code to initialize it.

The field keyword is planned for a future version of C# (it did not make it into C# 11 and will probably not make it into C# 12) and allows the access to the automatically created backing field.

// Removes time part in setter
public DateTime HiredDate { get; init => field = value.Date(); }

public Data LazyData => field ??= new Data();
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
  • 2
    Great answer, thanks. For db operation it would look something like this: `IQueryable result = db.Set().Find(//just id here//).ToList();` It would already know that you are looking for primary key. Just for info. – Mr. Blond Oct 09 '14 at 19:34
  • I know this is an old answer, but I'd separate the get and set into different methods so that the value is not accidentally set during a comparison. – Joel Trauger Oct 11 '16 at 19:08
  • @JoelTrauger: A comparison reads the property and therefore only calls the getter. – Olivier Jacot-Descombes Oct 11 '16 at 19:36
  • This is true, but an accidental assignment will call the setter and modify the property. See `return object.property = value` vs `return object.property == value` – Joel Trauger Oct 13 '16 at 14:58
  • An accidental call of a separate set method will modify the property as well. I don't see how separate get set methods can improve safety. – Olivier Jacot-Descombes Oct 13 '16 at 16:26
24
var list = new List<MyClass>();
var item = list.Find( x => x.GetId() == "TARGET_ID" );

or if there is only one and you want to enforce that something like SingleOrDefault may be what you want

var item = list.SingleOrDefault( x => x.GetId() == "TARGET" );

if ( item == null )
    throw new Exception();
zellio
  • 31,308
  • 1
  • 42
  • 61
13

Try:

 list.Find(item => item.id==myid);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Amritpal Singh
  • 1,765
  • 1
  • 13
  • 20
7

Or if you do not prefer to use LINQ you can do it the old-school way:

List<MyClass> list = new List<MyClass>();
foreach (MyClass element in list)
{
    if (element.GetId() == "heres_where_you_put_what_you_are_looking_for")
    {

        break; // If you only want to find the first instance a break here would be best for your application
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bjørn
  • 1,138
  • 2
  • 16
  • 47
5

You can also use LINQ extensions:

string id = "hello";
MyClass result = list.Where(m => m.GetId() == id).First();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
4

You can solve your problem most concisely with a predicate written using anonymous method syntax:

MyClass found = list.Find(item => item.GetID() == ID);
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
1
public List<DealsCategory> DealCategory { get; set; }
int categoryid = Convert.ToInt16(dealsModel.DealCategory.Select(x => x.Id));
  • While this code may answer the question, it is better to explain how to solve the problem and provide the code as an example or reference. Code-only answers can be confusing and lack context. – Robert Columbia Jun 20 '18 at 12:48
0

You can create a search variable to hold your searching criteria. Here is an example using database.

 var query = from o in this.mJDBDataset.Products 
             where o.ProductStatus == textBox1.Text || o.Karrot == textBox1.Text 
             || o.ProductDetails == textBox1.Text || o.DepositDate == textBox1.Text 
             || o.SellDate == textBox1.Text
             select o;

 dataGridView1.DataSource = query.ToList();

 //Search and Calculate
 search = textBox1.Text;
 cnn.Open();
 string query1 = string.Format("select * from Products where ProductStatus='"
               + search +"'");
 SqlDataAdapter da = new SqlDataAdapter(query1, cnn);
 DataSet ds = new DataSet();
 da.Fill(ds, "Products");
 SqlDataReader reader;
 reader = new SqlCommand(query1, cnn).ExecuteReader();

 List<double> DuePayment = new List<double>();

 if (reader.HasRows)
 {

  while (reader.Read())
  {

   foreach (DataRow row in ds.Tables["Products"].Rows)
   {

     DuePaymentstring.Add(row["DuePayment"].ToString());
     DuePayment = DuePaymentstring.Select(x => double.Parse(x)).ToList();

   }
  }

  tdp = 0;
  tdp = DuePayment.Sum();                        
  DuePaymentstring.Remove(Convert.ToString(DuePaymentstring.Count));
  DuePayment.Clear();
 }
 cnn.Close();
 label3.Text = Convert.ToString(tdp + " Due Payment Count: " + 
 DuePayment.Count + " Due Payment string Count: " + DuePaymentstring.Count);
 tdp = 0;
 //DuePaymentstring.RemoveRange(0,DuePaymentstring.Count);
 //DuePayment.RemoveRange(0, DuePayment.Count);
 //Search and Calculate

Here "var query" is generating the search criteria you are giving through the search variable. Then "DuePaymentstring.Select" is selecting the data matching your given criteria. Feel free to ask if you have problem understanding.