“用单一呼叫替换”是什么意思?

时间:2013-06-10 20:37:24

标签: c# .net linq

当使用LINQ with Single()时,我总是以绿色下划线代码,并提示“将单个调用替换为单个”。这是什么意思?以下是产生该建议的一行代码示例:

var user = db.Users.Where(u => u.UserID == userID).Single();

如你所见,我只使用Single()一次。那么......这是什么交易?

4 个答案:

答案 0 :(得分:42)

我认为这意味着,使用带有谓词的overload of Single,而不是一起使用WhereSingle

var user = db.Users.Single(u => u.UserID == userID);

答案 1 :(得分:8)

var user = db.Users.Single(u => u.UserID == userID)

句法糖

答案 2 :(得分:4)

一堆Linq表达式Enumerable Methods以这种方式工作,就像方法 Single 一样,它接受一个谓词并且仅在满足条件时才返回true(测试通过) ,否则是假的。

应该使用这些来代替Where()和Single():

var user = db.Users.Single(u => u.UserID == userID); 
// Checks for if there is one and, only one element that satisfy the condition.

var user = db.Users.Any(u => u.UserID == userID);  
// Checks for if there are any elements that satisfy the condition.

var user = db.Users.All(u => u.UserID == userID);  
// Checks if all elements satisfy the condition.

答案 3 :(得分:0)

使用两种方法从Linq Lambda中的(list,of,field)中的字段中选择*

  1. 使用“包含”
  2. 使用“加入”
  3. DotNetFiddle中的代码示例here

    enter image description here

    append=true
相关问题