![](/img/trans.png)
[英]Converting Dictionary<Int, Object> To Dictionary<Int, Object.Property> with lambdas
[英]Converting object property values to dictionary
可以說,我有一個像這樣的對象列表
public class Room{
public string Name {get; set;}
public int[] UserId {get; set;}
}
什么是將此列表轉換為字典的有效方式,如下所示
Dictionary<int, List<string>>
其中鍵是UserId,String是房間的名稱。 提前致謝。
我會使用Linq的Aggregate
方法,如下所示。 ( 注意我將原始對象的自由作為一個List vs一個數組用於演示,但你可以改變它 )。
var names = new List<Room>()
{
new Room() { Name = "Alpha", UserId = new List<int> { 10, 40 }},
new Room() { Name = "Omega", UserId = new List<int> { 10, 20, 30 }},
};
// Aggregate needs an item to pass around, we will
// seed it with the dictionary which will be the ultimate returned
// value. The following lambda takes a dictionary object (`dict`)
// and the current room ('current') to add to the dictionary.
names.Aggregate (new Dictionary<int, List<string>>(), (dict, current) =>
{
current.UserId.ForEach(id => {
if (dict.ContainsKey(id) == false)
dict.Add(id, new List<string>());
dict[id].Add(current.Name);
});
return dict;
});
結果:
概念
履行
foreach (Room r in RoomsList) {
foreach (int id in r.UserID) {
if (RoomDictionary.Contains(id))
RoomDictionary[id].Add(r.Name);
else
RoomDicationary.Add(id, new List<string>() { r.Name });
}
}
或者類似的東西,我只是在網絡瀏覽器中鍵入它,所以它可能需要一些調整,但類似的東西。
只是一些澄清,因為UserId被聲明為類Room中的數組。 假設它不是數組,1個id對應1個房間名稱。 實現IDictionary的RoomCollection將為您提供更好的控制,如下所示:
public class RoomCollection : IDictionary<int, string>
{
private Dictionary<int, string> roomCollection = new Dictionary<int, string>();
//Add modified version of Add()
public void Add(Room room)
{
//Do something to efficiently check whether room already exists
this.Add(room.UserId, room.Name);
}
public void Add(int key, string value)
{
//Checking can be done here
if (this.roomCollection.ContainsKey(key))
{
this.roomCollection[key] = value; //Overwrite values
}
else
{
this.roomCollection.Add(key, value); //Create new item
}
}
//Modify other functionalities to your own liking
public bool ContainsKey(int key)
{
return this.roomCollection.ContainsKey(key);
}
public ICollection<int> Keys
{
get { throw new NotImplementedException(); }
}
public bool Remove(int key)
{
throw new NotImplementedException();
}
public bool TryGetValue(int key, out string value)
{
throw new NotImplementedException();
}
public ICollection<string> Values
{
get { throw new NotImplementedException(); }
}
public string this[int key]
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public void Add(KeyValuePair<int, string> item)
{
throw new NotImplementedException();
}
public void Clear()
{
throw new NotImplementedException();
}
public bool Contains(KeyValuePair<int, string> item)
{
throw new NotImplementedException();
}
public void CopyTo(KeyValuePair<int, string>[] array, int arrayIndex)
{
throw new NotImplementedException();
}
public int Count
{
get { throw new NotImplementedException(); }
}
public bool IsReadOnly
{
get { throw new NotImplementedException(); }
}
public bool Remove(KeyValuePair<int, string> item)
{
throw new NotImplementedException();
}
public IEnumerator<KeyValuePair<int, string>> GetEnumerator()
{
throw new NotImplementedException();
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
}
public class Room
{
public string Name { get; set; }
public int UserId { get; set; }
}
public class TestCollection
{
public void Test()
{
Room r1 = new Room();
r1.UserId = 1;
r1.Name = "Room One";
Room r2 = new Room();
r2.UserId = 2;
r2.Name = "Room Two";
RoomCollection roomCollection = new RoomCollection();
roomCollection.Add(r1);
roomCollection.Add(r2);
foreach (int roomId in roomCollection.Keys)
{
Console.WriteLine("Room number: {0} - Room name: {1}", roomId, roomCollection[roomId]);
}
}
}
這似乎很直接:
var rooms = new List<Room>()
{
new Room() { Name = "Alpha", UserId = new List<int>() { 10, 40 }.ToArray() },
new Room() { Name = "Omega", UserId = new List<int>() { 10, 20, 30 }.ToArray() },
};
var query =
from r in rooms
from u in r.UserId
group r.Name by u;
var result = query.ToDictionary(x => x.Key, x => x.ToList());
我得到的結果是:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.