C# 使用 linq 枚举定义局部变量

C# Define local variable with an linq enumeration

我需要在 C# 枚举中定义一个局部变量,因为我有一个额外的枚举,它被多次调用导致效率低下。目前的代码如下所示:

List<object> listData = new List<object>();
List<EmployeeAdvanced> workDataList = GetEmployeeWorkAdvancedData();
List<EmployeeBasic> employeeList = GetEmployeeBasicData();

listData .AddRange(
          from employee in employeeList
          where employee.SomeNumber  > 0
             select new{
             ID = employee.ID,
             SSN = employee.SSN
             StreetAddress = workDataList.FirstOrDefault(x=> x.ID==employee.EmployeeID).Address,
             Zipcode = workDataList.FirstOrDefault(x=> x.ID==employee.EmployeeID).Zipcode}
);

我实际上有很多 workDataList 列表的枚举,但我每次都select使用相同的项目 (EmployeeID)。有什么方法可以让我只 select 我的个人 workDataList 对象一次,然后将它用于 select 循环中每个人的所有分配。

上面的代码是一个简化版本,所以名称、数据结构只是为了描述清楚而创建的。

如果我可以提供任何其他信息,请告诉我。

谢谢!

我想你正在寻找 let

List<object> listData = new List<object>();
List<EmployeeAdvanced> workDataList = GetEmployeeWorkAdvancedData();
List<EmployeeBasic> employeeList = GetEmployeeBasicData();

listData .AddRange(
          from employee in employeeList
          where employee.SomeNumber  > 0
          let workData = workDataList.FirstOrDefault(x=> x.ID==employee.EmployeeID)
             select new{
             ID = employee.ID,
             SSN = employee.SSN
             StreetAddress = workData.Address,
             Zipcode = workData.Zipcode}
);
listData.AddRange(from employee in employeeList
                  where employee.SomeNumber  > 0
                      let employeeTmp = workDataList.FirstOrDefault(x => x.ID == employee.EmployeeID)
                      select new {
                                    ID = employee.ID,
                                    SSN = employee.SSN
                                    StreetAddress = employeeTmp.Address,
                                    Zipcode = employeeTmp.Zipcode 
                                 }
);

You should use let keyword. Here 是对用法的彻底解释。