如何使用LINQ-c#

时间:2016-06-16 09:08:43

标签: c# .net linq

我有一个包含对象数组集合的List。我使用以下代码来收集所有EmployeeID

List<string> employeeIds= new List<string>();
var employeeFields = employees.Items.Select(c => c.EmployeeFields ).ToList();
foreach(var objectArray in employeeFields )
{
    foreach(var item in objectArray)
    {
        if(item is EmployeeID)
        {
            employeeIds.Add(item.ToString());
        }
    }
}

 public partial class EmployeeId 
  { private string itemField; /// <remarks/>           
    public string Item { get { 
  return this.itemField; } 
  set { this.itemField = value; }
 } 

}

这里EmployeeFields包含一个对象数组。如何在单个linq查询中执行此操作 实例http://rextester.com/VJB79010

2 个答案:

答案 0 :(得分:6)

您可以使用SelectManyOfType一次性执行此操作:

var employeeIds = employees.Items
    .Select(c => c.EmployeeFields)     // Select the fields per employee
    .SelectMany(fields => fields)      // Flatten to a single sequence of fields
    .OfType<EmployeeID>()              // Filter to only EmployeeID fields
    .Select(id => id.Item)             // Convert to strings
    .ToList();                         // Materialize as a list

或者代码行数略少,但理解起来可能更棘手:

var employeeIds = employees.Items
    .SelectMany(c => c.EmployeeFields) // Select the fields per employee and flatten
    .OfType<EmployeeID>()              // Filter to only EmployeeID fields
    .Select(id => id.Item)             // Convert to strings
    .ToList();                         // Materialize as a list

答案 1 :(得分:3)

这样的事情:

var employeeIds = employees.Items
                     .SelectMany(e => e.EmployeeFields )
                     .OfType<EmployeeID>()
                     .Select(f => f.Item)
                     .ToList();

实例:http://rextester.com/ZINFJN75313

编辑:更新了包含Item属性的类,而不是使用ToString