gpt4 book ai didi

c# - ToLookup() 如何使用多个索引?

转载 作者:太空狗 更新时间:2023-10-30 00:11:05 25 4
gpt4 key购买 nike

考虑到下面的 C# 控制台应用程序代码,使用

我应该如何修改它以替换行:

foreach (Product product in productsByCategory[category])

通过代码行

foreach (Product product in productsByCategory[category][Id])

?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace myQuestion
{
class Program
{
static void Main(string[] args)
{
var products = new List<Product>
{
new Product { Id = 1, Category = "Garden", Value = 15.0 },
new Product { Id = 1, Category = "Garden", 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 = 21.25 },
new Product { Id = 7, Category = "Pets", Value = 5.50 },
new Product { Id = 8, Category = "Garden", Value = 13.0 },
new Product { Id = 9, Category = "Automotive", Value = 10.0 },
new Product { Id = 10, Category = "Electronics", Value = 250.0 }
};


ILookup<string, Product> productsByCategory =
products.ToLookup( p => p.Category);
string category = "Garden";
int Id = 1;
foreach (Product product in productsByCategory[category])
{
Console.WriteLine("\t" + product);
}

Console.ReadLine();
}
}

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

更新:
这是一个人为的示例,旨在学习 C# 的概念 ToLookup Method .

作为引用,我是在阅读the David Andres' answer to question "What is the point of Lookup?" 后才想到这个问题的。 :

"A Lookup will map to potentially several values.  

Lookup["Smith"]["John"] will be a collection of size one billion."

我想重现。

还是我理解错了?

最佳答案

不确定我是否正确理解了您的需求,但您为什么不能这样做:

foreach (Product product in productsByCategory[category].Where(x=> x.Id == Id))

或者使用匿名对象:

var productsByCategory = products.ToLookup(p => new { p.Category, p.Id });
string category = "Groceries";
int Id = 1;
foreach (Product product in productsByCategory[new {Category = category, Id= Id}])
{
Console.WriteLine("\t" + product);
}

这是一个非常相似的问题,由 Servy 提供额外的解决方案

关于c# - ToLookup() 如何使用多个索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15734454/

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