C#范式:在列表副作用 [英] C# Paradigms: Side effects on Lists

查看:290
本文介绍了C#范式:在列表副作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想发展我的副作用的理解以及应如何进行控制和使用。

I am trying to evolve my understanding of side effects and how they should be controlled and applied.

在航班下面的列表,我想设置一个属性满足条件的每个航班的:

In the following List of flights, I want to set a property of each flight satisfying a conditions:

IEnumerable<FlightResults> fResults = getResultsFromProvider();

//Set all non-stop flights description
fResults.Where(flight => flight.NonStop)
        .Select(flight => flight.Description = "Fly Direct!");

在这个表达式中,我有我的名单上的副作用。从我有限的知识,我知道前。 LINQ用于的查询的唯一和只有少数操作列表和的分配的或设置值是不是其中之一和名单应该是一成不变的

In this expression, I have a side effect on my list. From my limited knowledge I know for ex. "LINQ is used for queries only" and "There are only a few operations to lists and assigning or setting values is not one of them" and "lists should be immutable".


  • 什么是错我的LINQ上述声明和应该怎样改?

  • 在哪里我可以在基本的情景我上面所描述的范例的更多信息?

  • What is wrong with my LINQ statement above and how should it be changed?
  • Where can I get more information on the fundamental paradigms on the scenario I have described above?

推荐答案

您LINQ代码不直接违反你提到的指导方针,因为你不是修改列表本身;你是刚刚修改的列表中的内容,一些属性。

Your LINQ code does not "directly" violate the guidelines you mention, because you are not modifying the list itself; you are just modifying some property on the contents of the list.

然而,驱使这些准则的主要理由仍然是:你不应该修改与LINQ数据(也,你是滥用选择来执行你的副作用)。

However, the main objection that drives these guidelines remains: you should not be modifying data with LINQ (also, you are abusing Select to perform your side effects).

不修改的任何的数据可以很容易地是合理的。考虑这个片断:

Not modifying any data can be justified pretty easily. Consider this snippet:

fResults.Where(flight => flight.NonStop)  

你看到这个被修改的飞行性能?也不会很多维修的程序员,因为他们将停止后其中,阅读 - 下面的代码的显然的无副作用,因为这是一个查询,请右键

Do you see where this is modifying the flight properties? Neither will many maintenance programmers, since they will stop reading after the Where -- the code that follows is obviously free of side effects since this is a query, right?

[鸡蛋里挑骨头?当然,看到一个查询的返回值是不保留的是,查询是否有副作用或代码应该有一个大破绽被删除;在任何情况下,说:什么是错的。但它是如此容易得多地说,当只有2行代码来看待,而不是在页页。]

[Nitpick: Certainly, seeing a query whose return value is not retained is a dead giveaway that the query does have side effects or that the code should have been removed; in any case, that "something is wrong". But it's so much easier to say that when there are only 2 lines of code to look at instead of pages upon pages.]

作为一个正确的解决方案,我会推荐这

As a correct solution, I would recommend this:

foreach (var x in fResults.Where(flight => flight.NonStop))
{
    x.Description = "Fly Direct!";
}



很容易写和读。

Pretty easy to both write and read.

这篇关于C#范式:在列表副作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆