如何简化这个LINQ语句?

编程入门 行业动态 更新时间:2024-10-25 18:33:10
本文介绍了如何简化这个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语句?

本文发布于:2023-10-27 00:18:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1531768.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语句   LINQ

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!