- Home /
C#, LINQ and Lists - help with 1 line of code?
Given an ItemID number (not the same as the Item[index_pos] in allItems List, I am able to retrieve an Item using:
QM_Items theItem = qmload.allItems.Where (x => x.iID == _iID).FirstOrDefault ();
Now I'd like to figure out how to get the index of allItems where the itemID (unique) is positioned. Per this http://stackoverflow.com/questions/2471588/how-to-get-index-using-linq
I was trying (pseudo):
myCars.Select((v, i) => new {car = v, index = i}).First(myCondition).index;
but unsure how to translate (myCondition) into my Unity project setup. Tried this:
int ItemINDEX = qmload.allItems.Select ((v,i) =>
new {QM_Items=v, index = i}).FirstOrDefault (v => v.QM_Items.iID => _iID).index;
but compiler doesn't like it or various forms I've attempted. Could someone more familiar with LINQ tell me how to write that?
Answer by KellyThomas · Jan 27, 2014 at 12:16 AM
My attempts to implement this using a purely LINQ approach lead to this:
int ItemINDEX = qmload.allItems.Where(x => x.iID == _iID)
.Select(x => qmload.allItems.IndexOf(x))
.FirstOrDefault();
The problem with this is that if no item with the correct iID
is in the collection it returns the default int (value of 0
) a result indistinguishable from when it matched the first item in the list. If instead we end the chain with .First()
it will throw an exception when no match is found.
Instead I recommend a hybrid approach:
int ItemINDEX = qmload.allItems.IndexOf(qmload.allItems.Where(x => x.iID == _iID)
.FirstOrDefault()
);
This will return the correct index (if a match is found) or -1
to indicate no match in the collection.
Your answer
Follow this Question
Related Questions
Get highest Vector3 from list (using Linq?) 1 Answer
Sort List by string field 1 Answer
Custom pathfinding and node-values 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers