转换此代码LINQ? [英] Convert this code to LINQ?

查看:145
本文介绍了转换此代码LINQ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,我只是拿起LINQ和它是比较新。



是否有可能转换到下列LINQ?

 的foreach(DataRow的行results.Rows)
{
如果(行[备注]的ToString()==通行证||行[备注]。的ToString()==提升)
{
结果= String.Concat(因此,行[ROLL_NO]的ToString(),);
}
}


解决方案

我们不知道是什么的结果是使这个棘手的,但假设你真正的初始值只想要一个空格分隔的列表,我应该这样做:

  VAR的查询=从DataRow的行result.Rows 
让言论=行[备注]。的ToString()
,其中言论==通行证||备注==提升
选择行[ROLL_NO]的ToString();

字符串结果=的string.join(,查询);



(注意:数据表未实现的IEnumerable< DataRow的方式> ,这就是为什么我使用显式类型范围变量另一种方法是调用 result.Rows.AsEnumerable() ,使隐式类型的。)



最后一行是假设.NET 4 ,这对的string.join 比早期版本更过载。否则,这将做到这一点:

 字符串结果=的string.join(,query.ToArray()); 



当然,如果你使用LINQ,那么你可能想从<$ C移开$ C>数据表等入手,并使用LINQ到SQL,实体框架,NHibernate的或任何其他可供选择:)


Sorry, Im just picking up LINQ and am relatively new at it.

Is it possible to convert the following into LINQ?

    foreach (DataRow row in results.Rows)
    {
        if (row["REMARKS"].ToString() == "Passes" || row["REMARKS"].ToString() == "Promoted")
        {
            result = String.Concat(result,row["ROLL_NO"].ToString()," ");
        }
    }

解决方案

We don't know what the initial value of result is which makes this tricky, but assuming you actually just want a space-separated list, I'd do this:

var query = from DataRow row in result.Rows
            let remarks = row["REMARKS"].ToString()
            where remarks == "Passes" || remarks == "Promoted"
            select row["ROLL_NO"].ToString();

string results = string.Join(" ", query);

(Note that DataTable doesn't implement IEnumerable<DataRow>, which is why I've used an explicitly typed range variable. An alternative would be to call result.Rows.AsEnumerable() and make row implicitly typed.)

The final line is assuming .NET 4, which has more overloads for string.Join than earlier versions. Otherwise, this would do it:

string results = string.Join(" ", query.ToArray());

Of course, if you're using LINQ then you may well want to move away from DataTable etc to start with and use LINQ to SQL, Entity Framework, nHibernate or any of the other options available :)

这篇关于转换此代码LINQ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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