使用LINQ到字典的新词典

Lui*_*uis 2 c# linq

我有Dictionary<Position, List<GameObject>>,我想创建一个新的字典Dictionary<Position, List<Person>>,收集包括至少一个人的职位List<GameObject>.

我试过了:

Dictionary<Position, List<Person>> persons =
    positions.ToDictionary(
        i => i.Key, 
        i => i.Value.Where(obj => obj is Person))
Run Code Online (Sandbox Code Playgroud)

positions 是第一本字典.

但它并没有真正起作用,因为这个位置有时是空的而且它不是真正的类型,Person因为你没有转换它.无论如何,你有什么想法吗?

Mar*_*zek 6

var people = positions.Select(x => new { x.Key, Values = x.Value.OfType<Person>().ToList() })
                      .Where(x => x.Values.Any())
                      .ToDictionary(x => x.Key, x => x.Values)
Run Code Online (Sandbox Code Playgroud)