Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将对象属性值转换为字典_C#_.net_Dictionary - Fatal编程技术网

C# 将对象属性值转换为字典

C# 将对象属性值转换为字典,c#,.net,dictionary,C#,.net,Dictionary,比如说,我有一个这样的对象列表 public class Room{ public string Name {get; set;} public int[] UserId {get; set;} } 以下哪种方法可以有效地将此列表转换为字典 Dictionary<int, List<string>> 字典 其中key是UserId,String是房间的名称。提前感谢。概念 遍历房间列表 如果词典包含 UserID将名称添加到关联列表中 否则就换一

比如说,我有一个这样的对象列表

public class Room{
    public string Name {get; set;}
    public int[] UserId {get; set;}
}
以下哪种方法可以有效地将此列表转换为字典

Dictionary<int, List<string>> 
字典

其中key是UserId,String是房间的名称。提前感谢。

概念

  • 遍历房间列表
  • 如果词典包含 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 });
    }
}
foreach(RoomsList中的r房间){
foreach(r.UserID中的int-id){
if(RoomDictionary.Contains(id))
RoomDictionary[id]。添加(r.Name);
其他的
添加(id,new List(){r.Name});
}
}

或者类似的东西,我只是把它输入到web浏览器中,所以它可能需要一些调整,但是类似的东西。

只是一些澄清,因为UserId是从教室声明为数组的。假设它不是数组,并且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]);
        }
    }
}
公共类RoomCollection:IDictionary
{
private Dictionary roomCollection=新建字典();
//添加Add()的修改版本
公共空间添加(房间)
{
//采取措施有效地检查房间是否已经存在
添加(room.UserId,room.Name);
}
公共void Add(int键,字符串值)
{
//检查可以在这里完成
if(此.roomCollection.ContainsKey(键))
{
this.roomCollection[key]=value;//覆盖值
}
其他的
{
this.roomCollection.Add(key,value);//创建新项
}
}
//根据自己的喜好修改其他功能
公共bool ContainsKey(int键)
{
返回此.roomCollection.ContainsKey(键);
}
公共ICollection密钥
{
获取{抛出新的NotImplementedException();}
}
公共布尔删除(int键)
{
抛出新的NotImplementedException();
}
公共bool TryGetValue(int键,out字符串值)
{
抛出新的NotImplementedException();
}
公共ICollection值
{
获取{抛出新的NotImplementedException();}
}
公共字符串此[int key]
{
得到
{
抛出新的NotImplementedException();
}
设置
{
抛出新的NotImplementedException();
}
}
公共作废添加(KeyValuePair项)
{
抛出新的NotImplementedException();
}
公共空间清除()
{
抛出新的NotImplementedException();
}
public bool包含(KeyValuePair项)
{
抛出新的NotImplementedException();
}
public void CopyTo(KeyValuePair[]数组,int-arrayIndex)
{
抛出新的NotImplementedException();
}
公共整数计数
{
获取{抛出新的NotImplementedException();}
}
公共图书馆是只读的
{
获取{抛出新的NotImplementedException();}
}
公共布尔删除(KeyValuePair项)
{
抛出新的NotImplementedException();
}
公共IEnumerator GetEnumerator()
{
抛出新的NotImplementedException();
}
IEnumerator IEnumerable.GetEnumerator()
{
抛出新的NotImplementedException();
}
}
公共教室
{
公共字符串名称{get;set;}
public int UserId{get;set;}
}
公共类TestCollection
{
公开无效测试()
{
房间r1=新房间();
r1.UserId=1;
r1.Name=“一号房间”;
房间r2=新房间();
r2.UserId=2;
r2.Name=“第二房间”;
RoomCollection RoomCollection=新建RoomCollection();
roomCollection.Add(r1);
roomCollection.Add(r2);
foreach(roomCollection.key中的int roomId)
{
WriteLine(“房间号:{0}-房间名:{1}”、roomId、roomCollection[roomId]);
}
}
}

我将使用Linq的
聚合方法,如下所示。(注意,在演示中,我随意使用原始对象作为列表而不是数组,但您可以更改它)

var name=新列表()
{
new Room(){Name=“Alpha”,UserId=新列表{10,40},
new Room(){Name=“Omega”,UserId=新列表{10,20,30},
};
//聚合需要一个项目来传递,我们将
//用最终返回的字典来播种它
//价值观。以下lambda接受dictionary对象(`dict`)
//以及要添加到词典的当前文件室(“当前”)。
names.Aggregate(新字典(),(dict,current)=>
{
current.UserId.ForEach(id=>{
if(dict.ContainsKey(id)=false)
dict.Add(id,newlist());
dict[id].Add(current.Name);
});
返回命令;
});
结果:


这似乎很直截了当:

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());
var rooms=新列表()
{
new Room(){Name=“Alpha”,UserId=new List(){10,40}.ToArray()},
new Room(){Name=“Omega”,UserId=new List(){10,20,30}.ToArray()},
};
变量查询=
从房间里的r
来自r.UserId中的u
组r。按u命名;
var result=query.ToDictionary(x=>x.Key,x=>x.ToList());
我得到的结果是:

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