8

现在我们有了 LINQ 的强大功能,我想知道哪种语法更可取。例如,我找到了以下方法(只是认为这是一个很好的例子):

foreach (FixtureImageServicesData image in _fixture.Images)
{
    if (image.Filename != _selectedFixtureImage.Filename && image.IsPrimary)
    {
        image.IsPrimary = false;
        image.IsChanged = true;
    }
}

如果我们将其转换为 LINQ 方法,它看起来像这样(未经测试):

_fixture.Images.Where(x => x.Filename != _selectedFixtureImage.Filename && x.IsPrimary).ForEach(x => { x.IsPrimary = false; x.IsChanged = true; });

您更愿意看到和维护哪个?这是疯子还是天才?

4

3 回答 3

22

使用ForEach扩展方法是可以的,但有一种中间方法:

// Rename 'query' to something meaningful :)
var query = _fixture.Images
                    .Where(image => _selectedFixtureImage.Filename 
                                    && image.IsPrimary);

foreach (FixtureImageServicesData image in query)
{
    image.IsPrimary = false;
    image.IsChanged = true;
}

如果您确实使用了一种ForEach方法,我肯定会将其格式化为多行:

_fixture.Images
    .Where(image => _selectedFixtureImage.Filename && image.IsPrimary)
    .ForEach(image => { image.IsPrimary = false; image.IsChanged = true;});

(减少缩进以避免缠绕......)

或者:

_fixture.Images
        .Where(image => _selectedFixtureImage.Filename && image.IsPrimary)
        .ForEach(image => { image.IsPrimary = false; 
                            image.IsChanged = true; });

您甚至可能希望将“制作非主要”位提取到一个单独的方法中,此时您将拥有:

_fixture.Images
        .Where(image => _selectedFixtureImage.Filename && image.IsPrimary)
        .ForEach(MakeNonPrimary);
于 2009-02-25T14:38:52.120 回答
2

这让我想起了“我应该使用 Regex 还是标准字符串函数”或“我应该使用 XSLT/XPATH 来转换 XML 还是使用 SelectSingleNode()”。

第一个选项(即 Regex/XSLT/Linq)通常被任何花了一些时间学习它的人认为更优雅、更强大。

而对于其他所有人来说,与第二个选项(即字符串函数、SelectSingleNode()、简单的 foreach 循环)相比,它的可读性较差且更复杂。

过去,我被指责在我的设计中使用 Regex 和 XSLT/XPATH 使事情变得过于复杂。

Just recently I was accused of being "scared of change" by preferring simple foreach (and even for) loops in many situations over Linq Where, Foreach etc.

I soon realised that the people in both cases who said this were the sort who feel that there is "the one way" to do everything.

Whereas I've always found it's much smarter to consider each situation on its merits and choose the right tool for the job. I just ignore them and continue with my approach ;)

For that situation you describe, the first option is more preferable to me. However I probably would use the Linq approach if my team were all competent in Linq, and we had coding guidelines to avoid big one-liners (by splitting it them up)

于 2009-02-25T15:05:18.950 回答
1

任何降低垂直或水平复杂性的东西对我来说都是一个加分项。此外,Linq 更能描述您要完成的工作。

于 2009-02-25T14:38:59.357 回答