c# - 如何通过属性值从字典中获取项目

标签 c# linq lambda

我有一个 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/

相关文章:

c# - 更新面板内的 Page.Unload 事件

linq - EF.Functions.Contains 包括多个关键字

python - 在运行时创建一个 python 函数来匹配可变数量的字典条目

c# - 如何防止 ReSharper 在方法调用中包装 lambda 表达式

c# - 迭代 Linq 结果时异常缓慢

android - Android Lambda 的 NoSuchMethodError

c# - Interop Word - 从文档中删除页面

c# - 在 C# 中在 Windows 7 上注册 dll

c# - 解决 CompositeCollection 中缺少分组的问题

linq - 无法创建类型 (type) 的常量值 在此上下文中仅支持原始类型 ('such as Int32, String, and Guid' )