c# - 如何在 Observable Collection 中搜索项目并获取其索引

标签 c# .net struct observablecollection

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 添加到 quantity

最佳答案

使用 LINQ :-)

var q =  PLUList.Where(X => X.ID == 13).FirstOrDefault();
if(q != null) 
{
   // do stuff
}
else 
{
   // do other stuff
}

如果你想将其保留为一个结构,请使用它:

var q =  PLUList.IndexOf( PLUList.Where(X => X.ID == 13).FirstOrDefault() );
if(q > -1) 
{
   // do stuff
}
else 
{
   // do other stuff
}

关于c# - 如何在 Observable Collection 中搜索项目并获取其索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9328575/

相关文章:

c# - 使用 StringFormat 转换为字符串

c# - 使用 C# 解析结果中的 JSON 数据

c# - Visual Studio Express ClickOnce - 无法使用应用程序发布 .NET 4.5 脱机安装程序

c# - 如何为应用程序设置 C# 库路径?

c# - 如何告诉 C# 使用哪个配置文件?

arrays - 使用 UILocalizedIndexedCollat​​ion.section(对于 : collationStringSelector:) with array of structs

c# - 在滚动 SPA 时,父 div 向上移动太远后,WebDriver 将子 div 报告为 "Not Visible"

c# - 如何将 System.Drawing.Icon 转换为 System.Drawing.Image?

c - 即使使用语法 &(struct_pointer->struct_var) 在 scanf 中使用结构指针也不起作用

C#:如何声明多个相似的结构?