How to search for an item and get its index in the 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>(); 

I have an ObservableCollection as above. Now I want to find the identifier in PLUList and get its index as follows:

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

What is the quick fix?

EDIT:

Suppose some elements have been added to the PLUList, and I want to add another new element. But before adding, I want to check if an identifier exists in the list. If this happens, I would like to add +1 to the quantity.

+4
source share
4 answers

Use LINQ :-)

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

Use this if you want to keep it in a structure:

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

If you want to get an item from your list, just use LINQ:

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

But this will return the element itself, not its index. Why do I need an index?

In addition, you should use class instead of struct if possible. Then you can check item for null to see if the identifier is found in the collection.

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

Here is a quick fix.

 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 ... 
+2
source

This is just an ordinary collection. Why can't you just iterate over it, check the id and return the index of the object. What is the problem?

 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.. } 

EDIT : 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 ); } 
+1
source

Source: https://habr.com/ru/post/1397029/


All Articles