如何在 Observable Collection 中搜索项目并获取其索引
public struct PLU
{
public int ID { get; set; }
public string name { get; set; }
public double price { get; set; }
public int quantity {get;set;}
}
public static ObservableCollection<PLU> PLUList = new ObservableCollection<PLU>();
我有上面的 ObservableCollection
。现在我想在 PLUList
中搜索 ID
并获取其索引,如下所示:
int index = PLUList.indexOf();
if (index > -1)
{
// Do something here
}
else
{
// Do sth else here..
}
有什么快速修复方法?
编辑:
假设一些项目已添加到 PLUList
中,并且我想添加另一个新项目。但在添加之前,我想检查 ID
是否已存在于列表中。如果确实如此,那么我想为数量
添加+1。
public struct PLU
{
public int ID { get; set; }
public string name { get; set; }
public double price { get; set; }
public int quantity {get;set;}
}
public static ObservableCollection<PLU> PLUList = new ObservableCollection<PLU>();
I have the ObservableCollection
as above. Now I want to search the ID
in the PLUList
and get its index like this:
int index = PLUList.indexOf();
if (index > -1)
{
// Do something here
}
else
{
// Do sth else here..
}
What's the quick fix?
EDIT:
Let's assume that some items were added to PLUList
and I want to add another new item. But before adding I want to check if the ID
already exists in the list. If it does then I would like to add +1 to the quantity
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用 LINQ :-)
如果你想将其保留为结构体,请使用它:
Use LINQ :-)
Use this, if you want to keep it a struct:
如果您想从列表中检索项目,只需使用 LINQ:
但这将返回项目本身,而不是其索引。为什么要索引?
另外,如果可能的话,您应该使用
class
而不是struct
。然后,您可以针对null
测试item
以查看是否在集合中找到了ID
。If you want to retrieve the item from your list, just use LINQ:
But this will return the item itself, not its index. Why do you want the index?
Also, you should use
class
instead ofstruct
if possible. Then you could testitem
againstnull
to see if theID
was found in the collection.虽然这篇文章很旧并且已经得到回答,但它仍然对其他人有帮助,所以我在这里是我的答案。
您可以创建类似于
List.FindIndex(...)
方法的扩展方法:用法:
Although this post is old and already answered, it can still be helpful to others so I here is my answer.
You can create extension methods similar to
List<T>.FindIndex(...)
methods:Usage:
这是一个快速修复。
Here is a quick fix.
这只是一个普通的集合。您可以迭代它,检查 ID 并返回对象的索引。
林克版本:
It's just a normal collection. You can just iterate over it, check the
ID
and return the index of the object.LINQ VERSION: