C# 在不使用循环的情况下在 ObservableCollection 中查找项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10498325/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 14:04:36  来源:igfitidea点击:

Find Item in ObservableCollection without using a loop

c#wpfcollections

提问by PeterP

Currently i have the following syntax (list is a list containing objects with many different properties (where Title is one of them):

目前我有以下语法(列表是一个包含具有许多不同属性的对象的列表(其中标题是其中之一):

for (int i=0; i < list.Count; i++)
{
   if(title == list[i].Title)
   {
    //do something
   }
}

How can i access the list[i].Titlewithout having to loop over my entire collection? Since my list tends to grow large this can impact the performance of my program.

我如何访问list[i].Title而不必遍历我的整个集合?由于我的列表往往会变大,这会影响我的程序的性能。

I am having a lot of similar syntax across my program (accessing public properties trough a for loop and by index). But im a sure there must be a better and elegant way of doing this?

我的程序中有很多类似的语法(通过 for 循环和索引访问公共属性)。但我确定一定有更好和优雅的方式来做到这一点?

The find method does seem to be a option since my list contains objects.

find 方法似乎是一个选项,因为我的列表包含对象。

采纳答案by Tigran

I Don't know what do you mean exactly, but technially speaking, this is not possible withouta loop.

我不知道你到底是什么意思,但从技术上讲,没有循环是不可能的。

May be you mean using a LINQ, like for example:

可能您的意思是使用 LINQ,例如:

list.Where(x=>x.Title == title)

It's worth mentioning that the iteration over is not skipped, but simply wrapped into the LINQ query.

值得一提的是,没有跳过迭代,而是简单地包装到 LINQ 查询中。

Hope this helps.

希望这可以帮助。

EDIT

编辑

In other words if you reallyconcerned about performance, keep coding the way you already doing. Otherwise choose LINQ for more concise and clear syntax.

换句话说,如果您真的很关心性能,请继续按照您已经在做的方式进行编码。否则选择 LINQ 以获得更简洁明了的语法。

回答by Patryk ?wiek

Here comes Linq:

Linq 来了:

var listItem = list.Single(i => i.Title == title);

It throws an exception if there's no item matching the predicate. Alternatively, there's SingleOrDefault.

如果没有与谓词匹配的项目,它会抛出异常。或者,有SingleOrDefault.

If you want a collection of items matching the title, there's:

如果您想要与标题匹配的项目集合,则有:

var listItems = list.Where(i => i.Title ==  title);

回答by Dan Busha

You're looking for a hash based collection (like a Dictionary or Hashset) which the ObservableCollection is not. The best solution might be to derive from a hash based collection and implement INotifyCollectionChanged which will give you the same behavior as an ObservableCollection.

您正在寻找 ObservableCollection 不是的基于哈希的集合(如字典或哈希集)。最好的解决方案可能是从基于散列的集合派生并实现 INotifyCollectionChanged,这将为您提供与 ObservableCollection 相同的行为。

回答by Roberto

ObservableCollection is a list so if you don't know the element position you have to look at each element until you find the expected one.

ObservableCollection 是一个列表,因此如果您不知道元素位置,则必须查看每个元素,直到找到预期的元素。

Possible optimization If your elements are sorted use a binary search to improve performances otherwise use a Dictionary as index.

可能的优化 如果您的元素已排序,请使用二分搜索来提高性能,否则使用字典作为索引。

回答by Daren Thomas

Consider creating an index. A dictionary can do the trick. If you need the list semantics, subclass and keep the index as a private member...

考虑创建索引。字典可以解决问题。如果您需要列表语义,请子类化并将索引保​​留为私有成员...

回答by used2could

I'd suggest storing these in a Hashtable. You can then access an item in the collection using the key, it's a much more efficient lookup.

我建议将这些存储在哈希表中。然后您可以使用键访问集合中的项目,这是一种更有效的查找。

var myObjects = new Hashtable();
myObjects.Add(yourObject.Title, yourObject);
...
var myRetrievedObject = myObjects["TargetTitle"];

回答by memo

Well if you have N objects and you need to get the Title of all of them you have to use a loop. If you only need the title and you really want to improve this, maybe you can make a separated array containing only the title, this would improve the performance. You need to define the amount of memory available and the amount of objects that you can handle before saying this can damage the performance, and in any case the solution would be changing the design of the program not the algorithm.

好吧,如果您有 N 个对象并且需要获取所有对象的标题,则必须使用循环。如果你只需要标题并且你真的想改进它,也许你可以制作一个只包含标题的单独数组,这会提高性能。在说这会损害性能之前,您需要定义可用内存量和您可以处理的对象数量,并且在任何情况下,解决方案都是改变程序的设计而不是算法。

回答by haxpak

i had to use it for a condition add if you don't need the index

如果您不需要索引,我不得不将它用于条件添加

using System.Linq;

use

if(list.Any(x => x.Title == title){
// do something here
}

this will tell you if any variable satisfies your given condition.

这将告诉您是否有任何变量满足您的给定条件。

回答by mjordan

Maybe this approach would solve the problem:

也许这种方法可以解决问题:

int result = obsCollection.IndexOf(title);

IndexOf(T)
Searches for the specified object and returns the zero-based index of the first occurrence within the entire Collection.

IndexOf(T)
搜索指定的对象并返回整个集合中第一次出现的从零开始的索引。

(Inherited from Collection)

(继承自 Collection)

https://docs.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.observablecollection-1?view=netframework-4.7.2#methods

https://docs.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.observablecollection-1?view=netframework-4.7.2#methods

回答by Jan

An observablecollection can be a List

一个 observablecollection 可以是一个列表

{
    BuchungsSatz item = BuchungsListe.ToList.Find(x => x.BuchungsAuftragId == DGBuchungenAuftrag.CurrentItem.Id);
}