c# list find check if item exists code example

Example 1: c# verify in class exist in list

Item wonderIfItsPresent = ...
bool containsItem = myList.Any(item => item.UniqueProperty == wonderIfItsPresent.UniqueProperty);'

Example 2: c# object is in object list

public class A { public int Id {get;set;} public A() {} public A(int id) {Id = id;}}

List<A> list = new List<A>() { new A() { Id = 1}, new A() { Id = 2}};

bool containsItem = list.Any(item => item.Id == 3);
// this would return false.

Example 3: c# does value exist in list

public int GetItemFromList() {
	List<Item> list = new List<Item>(
      new Item(1),
      new Item(2),
      new Item(3)
    );

	Item testItem = new Item(1);

	// Inside FindIndex() you can specify a lambda expression where you
	// query if an item exists like a boolean test.
	int index = list.FindIndex(item => testItem.Id == item.Id);

	// in this case out testItem.Id (1) is equal to an item in the list
	if (index > -1)
	{
		// We get here with the index 0!
      	return index;
	}
}

public class Item
{
	public int Id { get; set; }
	public Item() { }
	public Item(int id)
	{
		Id = id;
	}
}

Tags:

Misc Example