簡體   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