当 linq 为您完成大部分工作时,不太清楚为什么要进行所有这些工作:
IEnumerable<Person> somePeople; // from wherever
somePeople.Where(x => x.CreateDate < new DateTime(2000,1,1))
.ForEach(x => x.PersonClassification = "Online");
只需从此处添加 ForEach,并注意为什么默认情况下不包含它的 proisos。
如果你想让 WhereCreatedBefore 更好,那么像这样一个简单的扩展:
static class PersonExtensions
{
public static bool WhereCreatedBefore(this Person p,
int year, int month, int day)
{
return p.CreateDate < new DateTime(year,month,day);
}
}
这本身很有用,并为您提供:
somePeople.Where(x => x.CreatedBefore(2000,1,1))
.ForEach(x => x.PersonClassification = "Online");
当简单地扩展 linq 为您提供的工具时,为什么要限制自己使事情变得更容易。
如果您想链接多个副作用,只需对 ForEach 进行简单的更改,如下所示:
public static IEnumerable<T> Modify<T>(
this IEnumerable<T> input, Action<T> action)
{
foreach (var x in input)
{
action(x);
yield return x;
}
}
给你:
somePeople.Where(x => x.CreatedBefore(2000,1,1))
.Modify(x => x.PersonClassification = "Online");
.Modify(x => x.LastModifiedBy = Environment.UserName);
或者,如果您使用它的语言集成部分:
(from p in somePeople where p.CreatedBefore(2000,1,1)) select p)
.Modify(p => p.PersonClassification = "Online");
.Modify(p => p.LastModifiedBy = Environment.UserName);
如果您真的*想要您可以编写一个 ClassifyAs 扩展,如下所示:
public static IEnumerable<Person> ClassifyAs(
this IEnumerable<Person> input, string classification)
{
foreach (var p in input)
{
p. PersonClassification = classification;
yield return p;
}
}
给你你的原件:
(from p in input where p.CreatedBefore(2000,1,1)) select p).ClassifyAs("Online");
这是一个班轮!不需要花哨的框架或类型层次结构,只需要一些有用的扩展方法。Linq 通常设计良好、实现良好、无处不在并且很好地集成到 c# 中。重新实现它的查询部分将是愚蠢和浪费的,你想要的是向它添加导致操作的副作用。这很好(你有可变对象,所以这几乎不会引起问题)只需添加这些操作。只是让他们继续产生他们的输入将使您的代码风格流利。