Reputation: 29
This method finds different dates and adds to dates array. Is it possible to make this method with linq/lambda?
public static void FindDates(DateTime[] dates, LinkedList<Letter> L, out int counter)
{
counter = 0;
foreach (var let in L)
{
if (!dates.Contains(let.Date))
{
dates[counter] = let.Date;
counter++;
}
}
}
Upvotes: 0
Views: 438
Reputation: 39007
You need to change the prototype of the method, but you can do something like:
public static IReadOnlyList<DateTime> FindDates(IEnumerable<Letter> L)
{
return L.Select(l => l.Date).Distinct().ToList();
}
The value of counter
can be retrieved easily by reading the Count
property of the result list.
Overall, it's a good practice to avoid side-effects in methods as much as possible. Modifying an array passed as a parameter like you do is a good way to get bitten later.
Also, since the Linq extension methods are defined on IEnumerable<T>
, we can change the parameter of the method to IEnumerable<Letter>
. It'll work exactly the same with your LinkedList<Letter>
, with the added benefit that it won't break if later you decide to use another collection type (such as List<Letter>
)
Upvotes: 2