C#列出<object>到Dictionary <key,<object >>

sup*_*ser 6 c# linq dictionary list

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

public class Person 
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

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

Dictionary<key, <Person>>
Run Code Online (Sandbox Code Playgroud)

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

我在网上找到了这个代码,但它可以使用 List<string>

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

小智 11

这适用于您的情况:

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

哪里personsList<Person>.


Ian*_*Ian 8

一个最直接的方法是使用int keykey是这样的:

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);
Run Code Online (Sandbox Code Playgroud)

关键是lambda表达式:

p => new { id = key++, person = p }
Run Code Online (Sandbox Code Playgroud)

您在哪里创建匿名object拥有idperson属性.它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);
Run Code Online (Sandbox Code Playgroud)

  • 感谢您提供非常完整的新手友好答案.我会在以后选择这个作为答案(回答太快5分钟) (2认同)