抱歉,我只是选择了LINQ并且相对较新。
是否可以将以下内容转换为LINQ?
foreach (DataRow row in results.Rows)
{
if (row["REMARKS"].ToString() == "Passes" || row["REMARKS"].ToString() == "Promoted")
{
result = String.Concat(result,row["ROLL_NO"].ToString()," ");
}
}
答案 0 :(得分:5)
我们不知道result
的初始值是什么使得这很棘手,但假设您实际上只是想要一个以空格分隔的列表,我会这样做:
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);
(请注意,DataTable
未实现IEnumerable<DataRow>
,这就是我使用明确类型的范围变量的原因。另一种方法是调用result.Rows.AsEnumerable()
并生成{{1隐式输入。)
最后一行是假设.NET 4,row
的重载次数比早期版本多。否则,这样做会:
string.Join
当然,如果您正在使用LINQ,那么您可能希望从string results = string.Join(" ", query.ToArray());
等开始,使用LINQ to SQL,实体框架,nHibernate或任何其他可用选项:)< / p>
答案 1 :(得分:2)
results.Rows
.Cast<DataRow>() // If you need this line or not depends on the type of result.Rows
.Where(row => row["REMARKS"].ToString() == "Passes" ||
row["REMARKS"].ToString() == "Promoted")
.Aggregate(result, (acc, row) => String.Concat(acc, row["ROLL_NO"].ToString()," "))
答案 2 :(得分:1)
result = results.Rows.Cast<DataRow>().Where(row => row["REMARKS"].ToString() == "Passes" || row["REMARKS"].ToString() == "Promoted").Aggregate(result, (current, row) => String.Concat(current, row["ROLL_NO"].ToString(), " "));
答案 3 :(得分:0)
string.Join(" ", result.Rows.Cast<DataRow>().Where(r => r["REMARKS"].ToString() == "Passes" || r["REMARKS"].ToString() == "Promoted").Select(r => r["ROLL_NO"].ToString()).ToArray());