For example, say I have a struct that represents a person and contains their name and age. I have an array of people, and now I want to find the person in that array that matches the name "John Doe". Doing some preliminary research has led me to Array.Find, but the way the documentation puts it is confusing. If someone can help me with this, it'd be greatly appreciated.
3 Answers
You can more easily use LINQ. First add using System.Linq and then write the following:
var john = people.FirstOrDefault( p => p.Name == "John Doe" );
Using Array.Find you would do:
var john = Array.Find( people, p => p.Name == "John Doe" );
I usually prefer the LINQ approach because it is more direct and readable as you can call the FirstOrDefault method directly on the array itself. Moreover you can use SingleOrDefault if you want to make sure there is only one instance that matches or throw exception or use First and Single to throw when nothing is found. The ...Default versions of these methods return default(T) when no match is found.
Comments
Try .Single(foo => foo.bar == "What you want.") from the linq extension methods on IEnumerable.
see: https://msdn.microsoft.com/en-us/library/bb155325(v=vs.110).aspx
Comments
Here is an implementation of Array.Find for you
using System;
public class Program
{
public static void Main()
{
var people = new [] {
new Person("Caleb"),
new Person("Martin"),
new Person("Shaun"),
new Person("Nechemia")
};
var result = Array.Find(people, person => person.Name == "Caleb");
Console.WriteLine(result.Name);
}
}
public struct Person
{
public readonly string Name;
public Person(string name)
{
Name = name;
}
}
Array.Find takes two arguments: the array to search and a predicate to run on each element.
A predicate is any function or method that takes an argument (person), checks it against a condition (person.Name == "Caleb"), and returns true or false.
In this case, Array.Find takes the array of people, checks them one at a time against the condition that the predicate defines, and returns the first person that meets that condition.