I'm writing LINQ operations by myself. At the moment, I'm having trouble with where. Take a look at my code, this is MyWhere
method:
public static T MyWhere<T>(this IEnumerable<T> myLst, Predicate<T> predicate)
{
T whereItem = default;
foreach (var item in myLst)
{
if (predicate.Invoke(item))
{
whereItem = item;
continue;
}
}
return whereItem;
}
This is in main method:
var myWhereItem = fruits.MyWhere(fruit => fruit.Length < 6);
Console.Write("MyWhere: ");
foreach (string item in myWhereItem)
{
Console.Write(myWhereItem ", ");
}
How do I write Where method, currently it's LastOrDefault?
CodePudding user response:
Your MyWhere
method returns a single value, not an enumeration of values. In your example code you call MyWhere
which returns a single string
value, which you then try to assign to an explicitly-typed IEnumerable<string>
.
If you check the LINQ definition for From
you'll find that it actually returns an IEnumerable<TSource>
. If you're trying to replicate the LINQ functionality (which is probably a Really Bad Idea) the simplest option (in modern C#) is to use an enumerable method:
public static IEnumerable<T> MyWhere<T>(this IEnumerable<T> sequence, Predicate<T> predicate)
{
foreach (var item in sequence)
{
if (predicate(item))
yield return item;
}
}
(This is simply syntactic sugar (compiler-supported shorthand) to generate a complete IEnumerable<T>
implementation in the background, making it easier to implement.)
If you're just trying to figure out how LINQ works, it's not hard to read the actual source code for it.