Reputation: 87
If I have a class that looks like this:
class test
{
public int ID { get; set; }
public int OtherID { get; set; }
}
And makes a list of those objects:
private List<test> test = new List<test>();
If I wanna try to find an index in this I would write:
int index = test.FindIndex(item => item.ID == someIDvar);
But now I wonder if I can use this to make more than one condition without writing another function for it? Like if I want to check if ID matches with a var AND OtherID matches with another?
Upvotes: 0
Views: 1647
Reputation: 53958
Try this one:
int index = test.FindIndex(item => item.ID == someIDvar &&
item.OtherID == another);
In the above snippet we use the &&
operator. Using the above snippet you will get the index of the first element in the list called test, that has a specific ID and a specific OtherID.
Another approach would be this one:
// Get the first element that fulfills your criteria.
test element = test.Where((item => item.ID == someIDvar &&
item.OtherID == another)
.FirstOrDefault();
// Initialize the index.
int index = -1
// If the element isn't null get it's index.
if(element!=null)
index = test.IndexOf(element)
For further documentation, please take a look here List.FindIndex Method (Predicate).
Upvotes: 2
Reputation: 5402
No reason why you can't make your predicate more complicated:
int index = test.FindIndex(item => item.ID == someIDvar
&& item.OtherID == someOtherIDvar);
Upvotes: 0
Reputation: 56688
Literally with &&
(and) operator:
int index = test.FindIndex(item => item.ID == someIDvar
&& item.OtherID == otherIDvar);
Upvotes: 2