简体   繁体   English

包含使用Linq / Lambda的方法

[英]Contains method using Linq/Lambda

This method finds different dates and adds to dates array. 此方法查找不同的日期并将其添加到dates数组。 Is it possible to make this method with linq/lambda? 是否可以使用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++;
        }
    }
}

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. 通过读取结果列表的Count属性,可以轻松获取counter的值。

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> . 另外,由于Linq扩展方法是在IEnumerable<T>上定义的,因此我们可以将方法的参数更改为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> ) 它与LinkedList<Letter>完全相同,其附加好处是,如果以后您决定使用其他集合类型(如List<Letter> ),它将不会中断。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM