如何在linq中使用这个函数

how to use this function in linq

鉴于我们不能在这种情况下使用函数,在 Linq 查询中合并 GetPreferredName 函数的好方法是什么?

List<Employee> Employees = (from d in context.Employees
                            join a in context.Address on d.ID equals a.EmployeeID
                            select new Employee
                            {
                                Id = d.Id,
                                PreferredName = GetPreferredName(d.FirstName, d.MiddleName, d.LastName, d.Alias),
                                StreetAddress = a.StreetAddress 
                            }).ToList();

private string GetPreferredName(string firstName, string middleName, string lastName, string dnsName)
        {
            if (!string.IsNullOrEmpty(firstName))
            return firstName;
            else if (!string.IsNullOrEmpty(middleName))
                return middleName;
            else if (!string.IsNullOrEmpty(lastName))
                return lastName;
            else if (!string.IsNullOrEmpty(dnsName))
                return dnsName;

            return "";
        }

你可以做的是先从数据库中枚举,然后做一个新的 select 到 运行 你的额外代码:

var Employees = 
    (from d in context.Employees
    join a in context.Address on d.ID equals a.EmployeeID
    select new //select the important bits we'll need in memory
    {
        Employee = d,
        Address = a,
    })
    .AsEnumerable() //AsEnumerable() it to make it enumerate from the database, now everything you need is in memory
    .Select(x => new Employee
    {
        Id = x.Employee.Id,
        PreferredName = GetPreferredName(x.Employee.FirstName, x.Employee.MiddleName, x.Employee.LastName, x.Employee.Alias),
        StreetAddress = x.Address.StreetAddress 
    })
    .ToList();

此外,使用 linq,您不需要手动执行这些连接,您可以将其更改为:

var Employees = context.Employees.Select(e => 
    select new //select the important bits we'll need in memory
    {
        Employee = e,
        Address = e.Address, //join is done for you!
    })
    .AsEnumerable() //AsEnumerable() it to make it enumerate from the database, now everything you need is in memory
    .Select(x => new Employee
    {
        Id = x.Employee.Id,
        PreferredName = GetPreferredName(x.Employee.FirstName, x.Employee.MiddleName, x.Employee.LastName, x.Employee.Alias),
        StreetAddress = x.Address.StreetAddress 
    })
    .ToList();

你可以使用?? null-coalescing operator.

PreferredName = d.FirstName ?? d.MiddleName ?? d.LastName ?? d.Alias

或者?: conditional operator

PreferredName = (d.FirstName != null && d.FirstName != "") ? d.FirstName :
   ((d.MiddleName != null && d.MiddleName != "") ? d.MiddleName : 
   ((d.LastName != null && d.LastName != "") ? d.LastName : d.Alias))