C# get object from list where object.value equals

So I have a list of objects from a class. In this list I want to get the object where Table.name == "value"

Class Table{

    public string name;
    private string primarykey;
    private string[] columnNames;

    //some methods and functions
}

My question is there an efficient way to get the specified object from this list with linq for example or do I just loop through this with a basic searching algoritm.

With a basic search algoritm I mean:

foreach(Table t in tables)
{
    if(t.name == "value")
        return t;
}

So is there a more efficient way to do this with linq for example?

Jon Skeet
people
quotationmark

You can easily do it with LINQ, but it won't be more efficient:

var match = tables.FirstOrDefault(t => t.name == value);

Now match will be null if there are no tables matching that criterion. You need to work out what you want to happen in that case.

The LINQ code is shorter, but will still have to iterate over every table in the list until it finds a match.

You might want to consider a Dictionary<string, Table> to map names to tables - but obviously that requires that there's only a single table per name. Also, unless you really have a lot of tables, you may well find that it's no quicker really. It's O(1) (assuming no hash collisions) instead of O(n), but when n is small, O(n) is really pretty fast. I strongly suggest that you check whether this is actually a bottleneck before worrying about the efficiency of it.

people

See more on this question at Stackoverflow