2012-02-17 114 views
4
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,如上所示。现在我想搜索的ID在PLUList并获得它的索引是这样的:如何在Observable Collection中搜索项目并获取其索引

int index = PLUList.indexOf(); 
if (index > -1) { 
// Do something here 
} 
else { 
// Do sth else here.. 
} 

什么是速战速决?

编辑:

让我们假设,一些项目被添加到PLUList,我想添加一个新的项目。但在添加之前,我想检查列表中是否存在该ID。如果确实如此,我想为数量添加+1。

+0

我想只有搜索ID! – user995387 2012-02-17 12:57:34

回答

16

使用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 
} 
+0

由于结构不可为空,因此不能与'struct'结合使用。 – ken2k 2012-02-17 13:11:57

+0

这是一个结构。你不能测试它为null。 – 2012-02-17 13:12:50

+0

我需要将结构替换为类。谢谢:) – user995387 2012-02-17 13:13:30

3

如果你想从你的列表中检索项目,只需使用LINQ:

PLU item = PLUList.Where(z => z.ID == 12).FirstOrDefault(); 

但是,这将返回该项目本身,而不是它的索引。你为什么要索引?

此外,如果可能,您应该使用class而不是struct。然后,您可以测试itemnull以查看ID是否在集合中找到。

if (item != null) 
{ 
    // Then the item was found 
} 
else 
{ 
    // No item found ! 
} 
+2

关注downvote的评论? – ken2k 2012-02-17 13:10:51

+0

我认为这将是快速修复。谢谢.. – user995387 2012-02-17 13:13:02

1

这只是一个普通的集合。为什么你不能迭代它,检查ID并返回对象的索引。有什么问题?

int index = -1; 

for(int i=0;i<PLUList.Count;i++) { 
PLU plu = PLUList[i]; 
if (plu.ID == yourId) { 
    index = i; 
    break; 
} 
} 

if (index > -1) { 
// Do something here 
} 
else { 
// Do sth else here.. 
} 

编辑:LINQ VERSION

private void getIndexForID(PLUListint idToFind,ObservableCollection<PLU> PLUList) { 
    PLU target = PLUList.Where(z => z.ID == yourID).FirstOrDefault(); 
    return target == null ? -1 : PLUList.IndexOf (target); 
} 
2

这里是一个速战速决。

int findID = 3; 
int foundID= -1; 
for (int i = 0; i< PLUList.Count; i++) 
{ 
    if (PLUList[i].ID == findID) 
    { 
    foundID = i; 
    break; 
    } 
} 

// Your code. 
if (foundID > -1) { 
// Do something here 
... 
+0

这个回答有几个问题:1)循环守护中的'<='应该是'<',因为当循环进入最后一次迭代时,你将得到一个索引越界异常和2)需要要检查'PLUList [i] .ID == findID'。 – Strelok 2012-02-17 13:07:41

+0

@Strelok:看,这就是为什么intellisense是邪恶的!我不能只是键入一个文本框=)。无论如何,谢谢你的提示。 – 2012-02-17 13:11:14

+0

没有probs。对任何人都适用。 – Strelok 2012-02-17 13:19:19

相关问题