如何在linq中使用此功能

时间:2015-01-06 20:59:30

标签: c# .net 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 "";
        }

2 个答案:

答案 0 :(得分:3)

您可以做的是首先从数据库中枚举,然后执行新的选择以运行您的额外代码:

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();

答案 1 :(得分:1)

你可以用?? 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))