简体   繁体   English

如何将通用列表投影到字典中?

[英]How do you project a generic list into a dictionary?

Is there a simple, LINQ-only way to project a generic collection into a Dictionary, something which would eliminate the foreach in the following code block: 是否有一种简单的LINQ方法将泛型集合投影到Dictionary中,这将消除以下代码块中的foreach:

    Dictionary<int, Player> _rankedPlayers = new Dictionary<int,Player>();
    List<Player> rankedPlayers = Player.GetPlayers(Globals.FOOString, seasonCode);
    int i = 1;
    foreach (Player targetPlayer in rankedPlayers)
    {
      _rankedPlayers.Add(i, targetPlayer);
    }

You are looking for ToDictionary method 您正在寻找ToDictionary方法

var _rankedPlayers = Player.GetPlayers(Globals.FOOString, seasonCode)
      .Select((item, index) => new { item, index })
      .ToDictionary(x => index, x => x.item);

You can use the overload method of Enumerable.Select that produces an index of the element and project it into a dictionary using Enumerable.ToDictionary : 您可以使用Enumerable.Select的重载方法生成元素的索引,并使用Enumerable.ToDictionary其投影到字典中:

var rankedPlayers = Player.GetPlayers(Globals.FOOString, seasonCode)
    .Select((item, index) => Tuple.Create(item, index))
    .ToDictionary(item => item.Item1 + 1, item => i.Item2);

If your player list is too long, you might not feel comfortable creating a lot of Tuple instances and use an external index: 如果您的播放器列表太长,您可能Tuple创建大量的Tuple实例并使用外部索引:

var i = 0;
var rankedPlayers = Player.GetPlayers(Globals.FOOString, seasonCode)
    .ToDictionary(i => ++i, item => item.Item2);

Although this approach creates a new class for the closure over i . 虽然这种方法为i封闭创造了一个新的类。

If this is still too much for you, you can create your own extension: 如果这对您来说仍然太多,您可以创建自己的扩展:

public static class MyExtensions
{
    public static Dictionary<int, TSource> ToDictionary<TSource>(
        this IEnumerable<TSource> source)
    {
        var dictionary = new Dictionary<int, TSource>();
        var i = 0;
        foreach(var item in source)
        {
            dictionary.Add(++i, item);
        }
        return dictionary;
    }
}

But if you're using it only once, I would do it just like you did. 但如果你只使用它一次,我会像你一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM