gpt4 book ai didi

linq - 选择和选择很多不同

转载 作者:行者123 更新时间:2023-12-04 11:45:17 25 4
gpt4 key购买 nike

我已经阅读了许多关于 select 和 select many in LINQ 的站点/线程,但仍然不太明白。

select 是否返回集合中的一个元素并选择多个扁平化集合(例如 List>())?

谢谢

最佳答案

这是一个示例。希望它澄清一切:

static void MethodRun()
{
List<Topping> testToppings = new List<Topping> { Topping.Cheese, Topping.Pepperoni, Topping.Sausage };

var firstLetterofToppings = testToppings.Select(top => top.ToString().First());

// returns "C, P, S"

var singleToppingPizzas = testToppings.Select(top => new Pizza(top)).ToArray();

// returns "Pizza(Cheese), Pizza(Pepperoni), Pizza(Sausage)"

List<Topping> firstPizza = new List<Topping> { Topping.Cheese, Topping.Anchovies };
List<Topping> secondPizza = new List<Topping> { Topping.Sausage, Topping.CanadianBacon, Topping.Pepperoni };
List<Topping> thirdPizza = new List<Topping> { Topping.Ham, Topping.Pepperoni };

List<IEnumerable<Topping>> toppingsPurchaseOrder = new List<IEnumerable<Topping>> { firstPizza, secondPizza, thirdPizza };

var toppingsToOrder = toppingsPurchaseOrder.SelectMany(order => order);

//returns "Cheese, Anchovies, Sausage, CanadianBacon, Pepperoni, Ham, Pepperoni"

}

class Pizza
{
public List<Topping> Toppings { get; private set; }
public Pizza(Topping topping) : this(new List<Topping> { topping }) { }
public Pizza(IEnumerable<Topping> toppings)
{
this.Toppings = new List<Topping>();
this.Toppings.AddRange(toppings);
}
}

enum Topping
{
Cheese,
Pepperoni,
Anchovies,
Sausage,
Ham,
CanadianBacon
}

关键是 Select() 可以选择任何类型的对象。确实,您可以选择分配给集合的任何通用值的属性,但您也可以选择任何其他类型的对象。 SelectMany() 只是扁平化你的列表。

关于linq - 选择和选择很多不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2425571/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com