繁体   English   中英

C#列表 <object> 到字典 <key, <object> &gt;

[英]C# List<object> to Dictionary<key, <object>>

我是初学c#开发人员,我需要从列表中创建一个对象字典。 首先,让我将我的对象定义为Person。

public class Person 
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

现在我有一个我的人物对象列表。 List<Person>如何在LinQ中查询它以将其从我的列表中转换为Person of Dictionary? 我想要的输出是:

Dictionary<key, <Person>>

其中key是每个Person对象的递增整数..任何帮助都表示赞赏。 谢谢。

我在网上找到了这个代码,但它与List<string>

List<string> List1
var toDict = List1.Select((s, i) => new { s, i })
             .ToDictionary(x => x.i, x => x.s)

这适用于您的情况:

int key = 0; // Set your initial key value here.
var dictionary = persons.ToDictionary(p => key++);

personsList<Person>

一种最直接的方法是使用int key作为key如下所示:

List<Person> List1 = new List<Person>();
int key = 0; //define this for giving new key everytime
var toDict = List1.Select(p => new { id = key++, person = p })
    .ToDictionary(x => x.id, x => x.person);

关键是lambda表达式:

p => new { id = key++, person = p }

在哪里创建具有idperson属性的匿名object id是增量keyperson只是List<Person>的元素

如果您需要使用Person的Id,只需使用:

List<Person> List1 = new List<Person>();
var toDict = List1.Select(p => new { id = p.Id, person = p })
    .ToDictionary(x => x.id, x => x.person);

你几乎就在那里,只需将变量类型从List<string>更改为List<Person> ,你就可以了。 您可以按原样使用LINQ查询,例如:

List<Person> persons = new List<Person>();

var p1 = new Person();
p1.Name = "John";
persons.Add(p1);

var p2 = new Person();
p2.Name = "Mary";
persons.Add(p2);

var toDict = persons.Select((s, i) => new { s, i })
             .ToDictionary(x => x.i, x => x.s);

但是,虽然我没有任何针对LINQ的东西,但在这种特殊情况下,更易读的方法是使用这样的常规循环:

var result = new Dictionary<int, Person>();
for (int i = 0; i < persons.Count; i++)
{
    result.Add(i, persons[i]);
}

Jon Skeet使用Enumerable.Range 建议了另一种方法 ,我测试了它并完美地工作:

var toDict = Enumerable.Range(0, persons.Count)
             .ToDictionary(x => x, x => persons[x]);

这是我的解决方案:

var key = 0;
IDictionary<int, Person> personDictionary = personList
    .Select(x => new KeyValuePair<int,Person>(key++, x))
    .ToDictionary(y => y.Key, y => y.Value);

其中personListList<Person>

暂无
暂无

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

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