用字典中的值替换Linq查询中列表中的值

问题描述 投票:0回答:1

这在linq查询中。

我今天在Linq上遇到很多麻烦。

在Linq查询中考虑此行:

EnginePartNames = x.EngineParts.Select(t => t.PartId).ToList(),

左侧,EnginePartNames是字符串类型的ICollection。

右侧x.EngineParts.Select(t => t.PartId).ToList()是long类型的通用列表。

我有这本字典:

Dictionary<int, string> partName = new Dictionary<int, string>()
        {
            {5763, "5.7 Engine"},
            {3511, "8-speed Transmission"},
            {8552, "Crankshaft"},
            {9127, "Cylinder Heads" }
        };

我将如何遍历linq查询中的右侧列表,并用partName字典中的字符串替换每个PartId?

我尝试过:

EnginePartNames = partName[x.EngineParts.Select(t => t.PartId)].ToList()

但是它给了我这个错误:

无法从'System.Collections.Generic.IEnumerable'转换为'int'

因此,我将select语句中的值(很长)转换为字典中的int时出现问题。

所以我尝试了这个:

EnginePartNames = partName[Convert.ToInt32(x.EngineParts.Select(t => t.PartId))].ToList()

并得到此错误:

无法隐式转换类型'System.Collections.Generic.List'到“ System.Collections.Generic.ICollection”。一个明确的转换存在(您是否缺少演员表?)

因此,我有点迷失了……我不知道下一步该怎么做...

有什么想法吗?

谢谢!

c# linq dictionary asp.net-core iqueryable
1个回答
2
投票

我想应该是这样的

EnginePartNames = x.EngineParts.Select(t => partName[t.PartId]).ToList()

您可以通过键从字典中获得零件名称,由PartId表示。它起作用,因为indexerIDictionary<TKey,TValue>接受TKey类型的参数并返回TValue类型的值

© www.soinside.com 2019 - 2024. All rights reserved.