Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is List.Find<T> considered dangerous? What's a better way to do List<T>.Find(Predicate<T>)?

Tags:

c#

.net

I used to think that List<T> is considered dangerous. My point is that, I think default(T) is not a safe return value! Many other people think so too Consider the following:

List<int> evens = new List<int> { 0, 2, 4, 6, , 8};
var evenGreaterThan10 = evens.Find(c=> c > 10);
// evenGreaterThan10 = 0 #WTF

default(T) for value types is 0, hence 0 is goona be returned is the above code segment!
I didn't like this, so I added an extension method called TryFind that returns a boolean and accepts an output parameter besides the Predicate, something similar to the famous TryParse approach.
Edit:
Here's my TryFind extension method:

public static bool TryFind<T>(this List<T> list, Predicate<T> predicate, out T output)  
{  
  int index = list.FindIndex(predicate);  
  if (index != -1)  
  {  
    output = list[index];  
    return true;  
  }  
  output = default(T);  
  return false;  
}  

What's a your way to do Find on generic Lists?

like image 884
Galilyou Avatar asked Jul 08 '10 10:07

Galilyou


People also ask

What does find return if nothing is found C#?

Find() would return null when the condition wasn't satisfied.

How do you check if a value exists in a list C#?

public bool Contains (T item); Here, item is the object which is to be locate in the List<T>. The value can be null for reference types. Return Value: This method returns True if the item is found in the List<T> otherwise returns False.

How check if list is empty C#?

Now to check whether a list is empty or not, use the Count property. if (subjects. Count == 0) Console.

How do you check if a string exists in a list C#?

if (myList. Contains(myString)) string element = myList. ElementAt(myList. IndexOf(myString));


1 Answers

Instead of Find you could use FindIndex. It returns the index of the element found or -1 if no element was found.

http://msdn.microsoft.com/en-us/library/x1xzf2ca%28v=VS.80%29.aspx

like image 120
sunside Avatar answered Nov 15 '22 16:11

sunside