22

将 LINQ 与 Single() 一起使用时,我的代码行总是带有绿色下划线,并带有“替换为对单个的单个调用”的建议。这是什么意思?这是导致该建议的一行代码示例:

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

如您所见,我只使用 Single() 一次。所以……有什么关系?

4

4 回答 4

51

我认为这意味着,使用带有谓词而不是一起使用and的重载SingleWhereSingle

var user = db.Users.Single(u => u.UserID == userID);
于 2013-06-10T20:38:24.613 回答
9
var user = db.Users.Single(u => u.UserID == userID)

语法糖

于 2013-06-10T20:38:32.923 回答
5

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

这些应该代替 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.
于 2014-03-30T13:16:14.473 回答
0

Select * from where field in (list, of,field) 可以在 Linq Lambda 中使用两种方法实现

  1. 使用“包含”
  2. 使用“加入”

DotNetFiddle中的代码示例

在此处输入图像描述

using System;
 using System.Linq;
using System.Collections;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {

    //Initializing a collection of 4 Employees fromthree Different departments <Name of Employee, Dept ID>
    List<KeyValuePair<string, int>> EmployeeDept = new List<KeyValuePair<string, int>> {
        new KeyValuePair<string, int> ("Gates",2),
        new KeyValuePair<string, int> ("Nadella",2),
            new KeyValuePair<string, int> ("Mark",3),
        new KeyValuePair<string, int> ("Pichai",4)
    };

    //Filter the Employees belongs to these department
    int[] deptToFilter ={3,4};

    //Approach 1 - Using COntains Method
    Console.WriteLine ("Approach 1 - Using Contains");
    Console.WriteLine ("==========================================");   
    var filterdByContains = EmployeeDept.Where(emp => deptToFilter.Contains(emp.Value));
    foreach (var dept3and4employees in filterdByContains)
    {
        Console.WriteLine(dept3and4employees.Key+" - "+dept3and4employees.Value);
    }

    //Approach 2 Using Join
    Console.WriteLine ("\n\nApproach 2 - Using Join");
    Console.WriteLine ("==========================================");   
    var filteredByJoin = EmployeeDept.Join(
        deptToFilter,
        empdept => empdept.Value, 
        filterdept => filterdept, 
        (empdep,filddep) => new KeyValuePair<string, int>(empdep.Key, empdep.Value)
    );

    foreach (var dept3and4employees in filteredByJoin)
    {
        Console.WriteLine(dept3and4employees.Key+" - "+dept3and4employees.Value);
    }

}
}
于 2016-11-24T23:58:54.683 回答