投影操作

投影是指将对象转换为新形式的操作。

选择

项目基于转换函数的值。

方法语法

// Select

var numbers = new int[] { 1, 2, 3, 4, 5 };

var strings = numbers.Select(n => n.ToString());

// strings = { "1", "2", "3", "4", "5" }

查询语法

// select

var numbers = new int[] { 1, 2, 3, 4, 5 };

var strings = from n in numbers
              select n.ToString();

// strings = { "1", "2", "3", "4", "5" }

SelectMany

投影基于变换函数的值序列,然后将它们展平为一个序列。

方法语法

// SelectMany

class Customer
{
    public Order[] Orders { get; set; }
}

class Order
{
    public Order(string desc) { Description = desc; }
    public string Description { get; set; }
}
...

var customers = new Customer[] 
{
    new Customer { Orders = new Order[] { new Order("O1"), new Order("O2") } },
    new Customer { Orders = new Order[] { new Order("O3") } },
    new Customer { Orders = new Order[] { new Order("O4") } },
};

var orders = customers.SelectMany(c => c.Orders);

// orders = { Order("O1"), Order("O3"), Order("O3"), Order("O4") }

查询语法

// multiples from

var orders = from c in customers
             from o in c.Orders
             select o;

// orders = { Order("O1"), Order("O3"), Order("O3"), Order("O4") }