简体   繁体   English

C#从列表中获取object.value等于的对象

[英]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" 在这个列表中我想得到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. 我的问题是有一个有效的方法从linq获取此列表中的指定对象,或者我只是通过基本的搜索算法循环这个。

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? 那么有没有一种更有效的方法来实现这一点,例如linq?

You can easily do it with LINQ, but it won't be more efficient: 您可以使用LINQ轻松完成,但效率不会更高:

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

Now match will be null if there are no tables matching that criterion. 如果没有与该条件匹配的表,则match将为null 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. LINQ代码较短,但仍需迭代列表中的每个表,直到找到匹配项。

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. 您可能需要考虑使用Dictionary<string, Table>将名称映射到表 - 但显然需要每个名称只有一个表。 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. 它是O(1)(假设没有哈希冲突)而不是O(n),但是当n很小时,O(n)真的非常快。 I strongly suggest that you check whether this is actually a bottleneck before worrying about the efficiency of it. 我强烈建议你在担心它的效率之前检查这是否真的是一个瓶颈。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM