使用Linq和C#比较列表数据

时间:2016-09-23 21:53:35

标签: c# linq

我有两个类列表,一个名为lsEmployee,另一个名为lsAccount。帐户列表只是帐户名称列表,员工列表中包含员工和帐户。我正在尝试使用linq查询来查看员工的帐户是否与帐户列表中的帐户匹配。

我是linq的新手,所以它可能只是一个语法问题。我尝试了以下代码,但我似乎无法使其工作。任何建议将不胜感激。

var lsEmployeeAccount = (lsAccount.Where(a => a.Account_Name == employee.Account_Name).SingleOrDefault()).ToString();

string lsEmployeeAccountString = lsEmployeeAccount.ToString() ?? "";

if (string.IsNullOrWhiteSpace(lsEmployeeAccountString))
{
//If account is not found, do stuff here

}
else
{
//If account is found, do stuff here
}

4 个答案:

答案 0 :(得分:0)

不确定您是先循环通过帐户或员工,但假设您正在通过每位员工:

foreach(var employee in lsEmployee)
{
  var isExist = lsAccount.Contain(employee.Account_Name);

  if(isExist)
  {}
  else
  {}
}

答案 1 :(得分:0)

你可以这样做:

var lsEmployeeAccount = lsAccount.SingleOrDefault(a => a.Account_Name == employee.Account_Name);
var lsEmployeeAccountString = (lsEmployeeAccount != null) ? lsEmployeeAccount.ToString() : "";

if (string.IsNullOrWhiteSpace(lsEmployeeAccountString))
{
    //If account is not found, do stuff here
}
else
{
    //If account is found, do stuff here
}

但请注意,lsEmployeeAccountString可能不会像您期望的那样出现。

答案 2 :(得分:0)

在连接包含不同类型数据的多个IEnumerable时,请考虑使用SQL样式LINQ语法;例如:

        var validAccounts = new[] {"1234", "2468", "1357", "6789", "9753", "9630"};
        var employees = new[]
        {
            new Employee {Name = "Bob", Account = "1357"},
            new Employee {Name = "Dave", Account = "1030"},
            new Employee {Name = "Fred", Account = "6789"},
            new Employee {Name = "Emma", Account = "2469"},
        };


        var employeesWithValidAccounts =
            from emp in employees
            join validAccount in validAccounts on emp.Account equals validAccount
            select emp.Name;

        foreach (var name in employeesWithValidAccounts)
        {
            Console.WriteLine(name);
        }

输出:

Bob
Fred

答案 3 :(得分:0)

如果您有SingleOrDefault并且没有匹配的帐户,那么您的lsEmployeeAccount为空,您将获得NullReferenceException。

将您的比较更改为

var lsEmployeeAccount = lsAccount.Where(a => a.Account_Name == employee.Account_Name).SingleOrDefault()
if (lsEmployeeAccount == null)
{
    //If account is not found, do stuff here
}
else
{
    //If account is found, do stuff here
}

如果您不需要该帐户,则另一种选择是

if (!lsAccount.Any(a => a.Account_Name == employee.Account_Name))
{
    //If account is not found, do stuff here
}
else
{
    //If account is found, do stuff here
}