简体   繁体   English

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

[英]C# Define local variable with an linq enumeration

I need to define a local variable within a C# enumeration as I have an additional enumeration with that which is called several times creating inefficiencies. 我需要在C#枚举中定义一个局部变量,因为我有一个额外的枚举,该枚举多次被称为创建效率低下。 The code currently looks like this: 当前代码如下:

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

I actually have numerous enumerations of the workDataList list, but I'm selecting on the same item each time (EmployeeID). 实际上,我有许多workDataList列表的枚举,但是每次都在同一项上选择(EmployeeID)。 Is there some way I can just select my individual workDataList object once, then use it for all assignments within each individual from select loop. 有什么方法可以只选择我的单个workDataList对象一次,然后将其用于select循环中每个个体内的所有分配。

The code above is a simplified version so names, data structures are just created for descriptive clarity. 上面的代码是简化的版本,因此仅为了描述清楚而创建了名称和数据结构。

Let me know if I can provide any additional information. 让我知道是否可以提供其他信息。

Thanks! 谢谢!

I think you're looking for let . 我认为您正在寻找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 the let keyword. 您应该使用let关键字。 Here is a thoroughly explanation of the usage. 是用法的完整说明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM