将对象属性值转换为字典

时间:2015-07-08 00:29:29

标签: c# .net dictionary

让我们说,我有一个像这样的对象列表

public class Room{
    public string Name {get; set;}
    public int[] UserId {get; set;}
}

将此列表转换为字典的有效方法如下

Dictionary<int, List<string>> 

其中键是UserId,String是房间的名称。在此先感谢。

4 个答案:

答案 0 :(得分:2)

我会使用Linq的Aggregate方法,如下所示。 (注意我将原始对象的自由视为演示的列表与数组,但您可以更改)。

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;
            });

结果:

enter image description here

答案 1 :(得分:1)

<强>概念

  • 浏览房间列表。
  • 如果字典包含 UserID将名称添加到关联列表。
  • 否则换个新的 字典项目。

<强>实施

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 });
    }
}

或类似的东西我只是在网络浏览器中键入它所以它可能需要一些调整,但类似的东西。

答案 2 :(得分:0)

稍微澄清一下,因为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]);
        }
    }
}

答案 3 :(得分:0)

这似乎很直接:

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());

我得到的结果是:

result