C# Find object in List<T>
c#, exists, find, list
Solution
You don't really need LINQ for this; there's the handy `List<T>.FindIndex` method
List<Foo> foos = ...
int index = foos.FindIndex(foo => foo != null && foo.Id == "CLR");
if(index != -1)
{
Foo replacement = ...
foos[index] = replacement;
}
else
{
Foo toAdd = ...
foos.Add(toAdd);
}
By the way, are you sure you don't actually need a lookup-table of some sort? Your usage pattern suggests you wan't a `Dictionary<string, Foo>` or similar rather than a list.
Problem
I have a List. I want to know how to write LINQ or so to find if their exists an obj of MyTypes whose id = "CLR". I would like to know if it exists and its index. So if it exists, then thru its index I can replace with a new object of MyTypes else add it. I know I cna do it thru iterating the items in List, but that will be time consuming than using LINQ statement. Correct me if am wrong. Can any provide help.