0

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++;
        }
    }
}
2
  • 1
    no you cant. because LinkedList does not supprot linq. however you can write your own extension which is not what you want. because you are doing it already with foreach loop. Commented May 22, 2016 at 9:16
  • 1
    If i'm not mistaken this function will replace existing dates in the dates field on the counter index, not actually expand it. Also it will go out of bounds if the counter reaches more than the previously defined dates length. I would rather use a List instead of an array. Then something like: var newDates = L.Where(letterDate => !dates.Contains(letterDate)); dates.AddRange(newDates); If you need the counter, it should equal newDates.Count Commented May 22, 2016 at 9:18

1 Answer 1

2

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>)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.