gpt4 book ai didi

c# - ToLookup() : access groups/items by numeric index?

转载 作者:行者123 更新时间:2023-11-30 20:21:34 32 4
gpt4 key购买 nike

我有以下产品列表

public sealed class Product
{
public int Id { get; set; }
public string Category { get; set; }
public double Value { get; set; }

public override string ToString()
{
return string.Format("[{0}: {1} - {2}]", Id, Category, Value);
}
}

var products = new List<Product>
{
new Product { Id = 1, Category = "Electronics", Value = 15.0 },
new Product { Id = 2, Category = "Groceries", Value = 40.0 },
new Product { Id = 3, Category = "Garden", Value = 210.3 },
new Product { Id = 4, Category = "Pets", Value = 2.1 },
new Product { Id = 5, Category = "Electronics", Value = 19.95 },
new Product { Id = 6, Category = "Pets", Value = 5.50 },
new Product { Id = 7, Category = "Electronics", Value = 250.0 },
};

您可以使用 ToLookup() 轻松查找列表中的值。

// create lookup
var productLookup = products.ToLookup(p => p.Category);

现在我想从中获取一些信息:

// get the number of categories/groups
Console.WriteLine(productLookup.Count());
// FAILS: get the number of items in the second category
Console.WriteLine(productLookup[2].Count());
// FAILS: get a certain item by numeric index (1: group | 3: item in group)
Console.WriteLine(productLookup[1][3]);

我必须使用数字索引并且不能使用 Category 字符串,除非我会创建另一个包含所有键的结构。

GroupBy()ToDictionary() 是否是更好的选择,或者我如何使用 ToLookup() 来做到这一点?

最佳答案

我看不出你不这样做的任何理由:

var productLookup = products.ToLookup(p => p.Category).Select(x => x.ToArray()).ToArray();

productLookup 的类型现在只是 Product[][]

然后您的代码运行正常(一旦您使用了有效的数组索引值):

Console.WriteLine(productLookup.Count());
Console.WriteLine(productLookup[2].Count());
Console.WriteLine(productLookup[0][2]);

这给了我:

results

关于c# - ToLookup() : access groups/items by numeric index?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33650420/

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