49

Suppose we have a class called Dog with two strings "Name" and "Id". Now suppose we have a list with 4 dogs in it. If you wanted to change the name of the Dog with the "Id" of "2" what would be the best way to do it?

Dog d1 = new Dog("Fluffy", "1");
Dog d2 = new Dog("Rex", "2");
Dog d3 = new Dog("Luna", "3");
Dog d4 = new Dog("Willie", "4");

List<Dog> AllDogs = new List<Dog>()
AllDogs.Add(d1);
AllDogs.Add(d2);
AllDogs.Add(d3);
AllDogs.Add(d4);
Bob.
  • 3,894
  • 4
  • 44
  • 76
John H.
  • 1,215
  • 3
  • 12
  • 15

3 Answers3

98
AllDogs.First(d => d.Id == "2").Name = "some value";

However, a safer version of that might be this:

var dog = AllDogs.FirstOrDefault(d => d.Id == "2");
if (dog != null) { dog.Name = "some value"; }
Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232
7

You could do:

var matchingDog = AllDogs.FirstOrDefault(dog => dog.Id == "2"));

This will return the matching dog, else it will return null.

You can then set the property like follows:

if (matchingDog != null)
    matchingDog.Name = "New Dog Name";
gleng
  • 6,185
  • 4
  • 21
  • 35
  • 7
    `FirstOrDefault` isn't really useful here. If it returns "default", it'll raise a `NullReferenceException` when you try to set `Name`... – Reed Copsey Oct 09 '13 at 19:36
  • 2
    that means it really IS useful here because if you just use .first, you'll get an exception doing the select itself. – John Lord Oct 22 '20 at 18:58
0

If the list is sorted (as happens to be in the example) a binary search on index certainly works.

    public static Dog Find(List<Dog> AllDogs, string Id)
    {
        int p = 0;
        int n = AllDogs.Count;
        while (true)
        {
            int m = (n + p) / 2;
            Dog d = AllDogs[m];
            int r = string.Compare(Id, d.Id);
            if (r == 0)
                return d;
            if (m == p)
                return null;
            if (r < 0)
                n = m;
            if (r > 0)
                p = m;
        }
    }

Not sure what the LINQ version of this would be.

  • Why reinvent that. [List.BinarySearch](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=2ahUKEwjMiZf1zMblAhXjQ98KHWYUCMwQFjAAegQIBRAG&url=https%3A%2F%2Flearn.microsoft.com%2Fen-us%2Fdotnet%2Fapi%2Fsystem.collections.generic.list-1.binarysearch&usg=AOvVaw2CwInMFi1iu3vXlCBu52yj) works great. – Suncat2000 Oct 31 '19 at 13:28