7

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?

3
  • 4
    linq doesn't make your code magically faster. So while you could use tables.Single(t => t.name == "value"), it will not be faster. Commented Jan 26, 2015 at 8:20
  • I am aware it doesnt make it faster, but it does make it more readable with linq Commented Jan 26, 2015 at 8:29
  • If you're interested in readability more than efficiency, please make sure that next time you indicate that in your question - you talk about "efficient" twice in the question, but never mention that you actually just want simpler code. Commented Jan 26, 2015 at 8:32

1 Answer 1

17

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.

Sign up to request clarification or add additional context in comments.

7 Comments

I believe it worth mention that LINQ will not make his code faster
@HossamBarakat: As I did, twice.
asked 4 mins ago, answered 3 mins ago. Skeet strikes again.
Oh Great, It seems that I was viewing old version !
I have a dictionary(list for testing) which contains the table details. They are used to generate a dynamic query. It saves the table name in the result of this query. Now in the result from this query I need to get the column names from the specified table and that is why I need this search algorithm. I am aware it does not make it faster but it does make it more readable. Thanks for this answer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.