通过将字符串类型列表设置为字典来创建字典

JTu*_*ney 1 c# linq dictionary

我试图使用类型字符串列表(productIds)创建此字典,但它是错误的:

出错的部分是p => p: 无法将类型'string'隐式转换为'System.Collections.Generic.IEnumerable'

这对我来说没有意义,因为p => p使得我这样做,所以我将一个字符串传递给第一个参数,然后将新的产品类别列表传递到第二个参数中.

Dictionary<string, IEnumerable<string>> missingProducts =
    productIds.ToDictionary<string, IEnumerable<string>>(
        p => p, p => p 
        new List<string>(productCategories));
Run Code Online (Sandbox Code Playgroud)

这是我在VB.NET中尝试转换的一个工作示例:

Dim productCategories As IList(Of String) = (From pc In prodCategories Select pc.CategoryName).ToList()

Dim missingProducts As Dictionary(Of String, IList(Of String)) = productIds.ToDictionary(Of String, IList(Of String))(Function(p) p, Function(p) New List(Of String)(productCategories))
Run Code Online (Sandbox Code Playgroud)

Pat*_*man 6

第二个参数ToDictionary是a Func(第一个:键选择器,第二个:值选择器),所以你也必须传入p.

第二:呼叫ToDictionary签名是错误的:

Dictionary<string, IEnumerable<string>> missingProducts =
productIds.ToDictionary<string, string, IEnumerable<string>>(
    p => p, 
    p => new List<string>(productCategories));
Run Code Online (Sandbox Code Playgroud)

  • @JTunney几乎相同,是的(它将是`Dictionary <string,List <string >>`).虽然仍然不相信每个产品应该具有相同的类别,但在您的用例中可能是正确的. (2认同)