可以'的'循环全部用LINQ语句来代替? [英] Can all 'for' loops be replaced with a LINQ statement?

查看:358
本文介绍了可以'的'循环全部用LINQ语句来代替?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能写入以下的foreach作为LINQ语句,我想更普遍的问题可以在任何for循环利用LINQ语句来代替。

Is it possible to write the following 'foreach' as a LINQ statement, and I guess the more general question can any for loop be replaced by a LINQ statement.

我不感兴趣的任何潜在的性能成本使用的是传统的命令式代码声明办法只是潜在的。

I'm not interested in any potential performance cost just the potential of using declarative approaches in what is traditionally imperative code.

    private static string SomeMethod()
    {
        if (ListOfResources .Count == 0)
            return string.Empty;

        var sb = new StringBuilder();
        foreach (var resource in ListOfResources )
        {
            if (sb.Length != 0)
                sb.Append(", ");

            sb.Append(resource.Id);
        }

        return sb.ToString();
    }



干杯

Cheers

AWC

推荐答案

当然。哎呀,你可以替换的算术的使用L​​INQ查询:

Sure. Heck, you can replace arithmetic with LINQ queries:

http://blogs.msdn.com/ericlippert/archive/2009/12/07/query-transformations-are-syntactic.aspx

但你不应该。

查询表达式的目的是的代表查询操作的。一个为循环遍历一个特定的语句,以便有其副作用,多次执行的目的。这些都是经常很大的不同。我鼓励取代环,其目的仅仅是查询与更高级别的结构更清楚地查询数据的数据。我极力劝阻与查询解析更换副作用生成代码,但这样做是可能的。

The purpose of a query expression is to represent a query operation. The purpose of a "for" loop is to iterate over a particular statement so as to have its side-effects executed multiple times. Those are frequently very different. I encourage replacing loops whose purpose is merely to query data with higher-level constructs that more clearly query the data. I strongly discourage replacing side-effect-generating code with query comprehensions, though doing so is possible.

这篇关于可以'的'循环全部用LINQ语句来代替?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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