Ata*_*600 146 linq dictionary
我正在尝试使用LINQ来创建Dictionary<string, List<CustomObject>>一个List<CustomObject>.我可以使用"var"来使用它,但我不想使用匿名类型.这就是我所拥有的
var x = (from CustomObject o in ListOfCustomObjects
group o by o.PropertyName into t
select t.ToList());
Run Code Online (Sandbox Code Playgroud)
我曾经尝试过使用Cast<>()LINQ库x,但是我遇到了编译问题,因为它是一个无效的强制转换.
Yur*_*ich 321
Dictionary<string, List<CustomObject>> myDictionary = ListOfCustomObjects
.GroupBy(o => o.PropertyName)
.ToDictionary(g => g.Key, g => g.ToList());
Run Code Online (Sandbox Code Playgroud)
Ruu*_*dvK 18
我无法评论@Michael Blackburn,但我猜你得到了downvote,因为在这种情况下GroupBy不是必需的.
使用它像:
var lookupOfCustomObjects = listOfCustomObjects.ToLookup(o=>o.PropertyName);
var listWithAllCustomObjectsWithPropertyName = lookupOfCustomObjects[propertyName]
Run Code Online (Sandbox Code Playgroud)
另外,我已经看到这种方式比使用GroupBy()更好.ToDictionary().