我有一个 Dictionary<string, User>
.
User
是具有属性 UID
的对象, UNIQUE KEY
和更多。我的字典键是 UNIQUE KEY
的用户。
现在,我想得到一个 User
来 self 的字典值 UID
而不是 key ,类似于ContainsKey
.. 它是如何用 lambda expr 或 linq 完成的?有好的解决方案吗?
最佳答案
这是一个工作示例:
using System;
using System.Collections.Generic;
using System.Linq;
internal class User
{
public string ID { get; set; }
public string Name { get; set; }
}
internal class Program
{
private static void Main(string[] args)
{
Dictionary<string, User> dic = new Dictionary<string, User>();
dic.Add("1", new User { ID = "id1", Name = "name1" });
dic.Add("2", new User { ID = "id2", Name = "name2" });
dic.Add("3", new User { ID = "id3", Name = "name3" });
User user = dic.Where(z => z.Value.ID == "id2").FirstOrDefault().Value;
Console.ReadKey();
}
}
关于c# - 如何通过属性值从字典中获取项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8617456/