【问题标题】:Drop 'Where' and move the condition into the 'First' in LINQ删除 'Where' 并将条件移动到 LINQ 中的 'First'
【发布时间】:2018-12-28 15:06:00
【问题描述】:

我有一个 Windows 应用程序,它有一些类似的代码,如下所示。
作为名为@9​​87654321@的类。

class Order{
 public string Orderid { get; set; }
 public string CustName { get; set; }
}

现在,在此应用程序的另一个类中,创建了 Order 类的对象并为其分配了值。

Order order = new Order();
order = JObject.Parse(some JSON data).ToObject<Order>();

现在我想根据来自order 的Orderid 提取CustName。为此,我使用了 LINQ。

string custName = order.Where(s => s.Key == "o123").First().Value;

我正在使用 Sonarqube 来检查代码质量。当我运行 SonarQube 工具时,它表明我需要在使用 LINQ 的地方重构我的代码。这是它显示的确切线。

Drop 'Where' and move the condition into the 'First'.

我已经搜索了很多,但无法理解它想说什么。谁能解释我如何重构这条线,使其通过 SonarQube 的期望。
任何意见都非常有帮助。谢谢。

【问题讨论】:

  • order.First(s =&gt; s.Key == "o123")

标签: c# linq sonarqube


【解决方案1】:

它告诉你的是Where是不必要的,代码可以这样表示:

string custName = order.First(s => s.Key == "o123").Value;

原代码的逻辑是这样的:

“查看列表以找到任何匹配项,并选择第一个”

与修改后的代码相同:

“取列表中的第一个匹配项”

请注意,如果没有匹配项,此代码将引发异常。如果有可能没有匹配的客户,请改用FirstOrDefault

string custName;
var customer = order.FirstOrDefault(s => s.Key == "o123");

if (customer != null) {
   custName = customer.Value;
}
else {
    // code to handle no match
}

【讨论】:

  • 如果null足够作为没有匹配的结果,可以缩短为string custName = order.FirstOrDefault(s =&gt; s.Key == "o123")?.Value
【解决方案2】:

当您可以使用 First lambda 表达式执行操作时,您分两步执行操作

string custName = order.First(s => s.Key == "o123").Value;

Linq 方法First 定义:

First<TSource>(this IEnumerable<TSource>, Func<TSource, Boolean>)
  • 第一个参数是您正在使用的 IEnumerable(Linq 是扩展方法)
  • 第二个参数允许你设置过滤器声明Func&lt;TSource, Boolean&gt;作为参数,你可以定义为s =&gt; s.Key == "o123"

【讨论】:

    猜你喜欢
    • 2019-07-18
    • 1970-01-01
    • 2012-09-02
    • 1970-01-01
    • 1970-01-01
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    • 2012-01-29
    相关资源
    最近更新 更多