本文介绍了如何简化这个LINQ语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
if (ds.Tables.Count > 0) { DataTable dt = ds.Tables[0]; if (dt.Rows.Count > 0) for (int i = 0; i < ds.Tables.Count; ++i) { listForHyphen.AddRange(ds.Tables[i].AsEnumerable().Distinct().Where(r => r.Field<Int64>("Action") == 1 && r.Field<string>("Terms")!= null).Select(r => "(" + r.Field<string>("Terms") + ")")); listForNdash.AddRange(ds.Tables[i].AsEnumerable().Distinct().Where(r => r.Field<Int64>("Action") == 0 && r.Field<string>("Terms")!= null).Select(r => "(" + r.Field<string>("Terms") + ")")); } }
在此i存储值在两个列表中,使用linq,任何可能缩短此语句,它检查列Action等于1或0并且其null或不为null,然后它将列条件中的值添加到列表
推荐答案与我见过的许多语句相比,LINQ语句并没有那么糟糕。为什么你认为它需要简化? 如果您只是想简化整个代码块,请对表中的行使用foreach语句,如下所示: The LINQ statement is not that bad compared to many I have seen. Why do you think it needs to be simplified? If you just want to simplify the entire block of code, use a foreach statement on the rows in the table like so: foreach (DataRow row in ds.Tables[0].Rows) { if ( Convert.ToInt64( row["Action"].ToString()) == 1 && !string.IsNullOrEmpty( row["Terms"].ToString() )) listForHyphen.Add( "(" + row["Terms"].ToString() + ")" ); if( Convert.ToInt64(row[ "Action" ].ToString()) == 0 && !string.IsNullOrEmpty(row[ "Terms" ].ToString()) ) listForNdash.Add("(" + row[ "Terms" ].ToString() + ")"); }
这将比使用LINQ更有效率,而且非常容易理解。
This will end up being more efficient than using the LINQ and is very easy to understand.
为什么循环遍历行集合? 这也应该有效: Why to loop through the collection of rows? This should works too: for (int i = 0; i < ds.Tables.Count; ++i) { listForHyphen.AddRange(ds.Tables[i].AsEnumerable().Distinct().Where(r => r.Field<Int64>("Action") == 1 && r.Field<string>("Terms")!= null).Select(r => "(" + r.Field<string>("Terms") + ")")); listForNdash.AddRange(ds.Tables[i].AsEnumerable().Distinct().Where(r => r.Field<Int64>("Action") == 0 && r.Field<string>("Terms")!= null).Select(r => "(" + r.Field<string>("Terms") + ")")); }
请参阅:List<t>.AddRange方法 [ ^ ]
更多推荐
如何简化这个LINQ语句?
发布评论