zoukankan      html  css  js  c++  java
  • c#字典怎么获取第一个键值 List<对象>获取重复项,转成Dictionary<key,List<对象>>

    c#字典怎么获取第一个键值

    Dictionary<string, int> dictionary = new Dictionary<string, int>();
    dictionary.Add("A1", 123);
    dictionary.Add("A2", 456);
    KeyValuePair<string,int> kvp=dictionary.FirstOrDefault();// 获取第一个
    Console.WriteLine("Key={0}	Value={1}",kvp.Key,kvp.Value);
    Console.WriteLine(dictionary.Keys.First());
    public class Car
        {
            public long ID { get; set; }
            public string Name { get; set; }
            public string OtherName { get; set; }
        }
    static void Main(string[] args)
            {
                List<Car> cars = new List<Car>();
                cars.Add(new Car() { ID = 1, Name = "红旗", OtherName = "hq1" });
                cars.Add(new Car() { ID = 2, Name = "奔驰", OtherName = "bc1" });
                cars.Add(new Car() { ID = 3, Name = "宝马", OtherName = "bm1" });
                cars.Add(new Car() { ID = 4, Name = "奔驰", OtherName = "bc2" });
                cars.Add(new Car() { ID = 5, Name = "宝马", OtherName = "bm2" });
    
    
                //同名
                var carSame = cars.GroupBy(x => x.Name).Where(x => x.Count() > 1).ToList();
                foreach (var item in carSame)
                {
                    Console.WriteLine(item.Key);
                }
    
    
                Console.WriteLine("---*---");
                var carSameArr = cars.GroupBy(x => x.Name).Where(x => x.Count() > 1).Select(i => i.Key).ToArray();
                foreach (string car in carSameArr)
                {
                    Console.WriteLine(car);
                }
    
    
                Console.WriteLine("---*---");
                var carDict = cars.GroupBy(x => x.Name).ToDictionary(x => x.Key, x => x.ToList());
                //以下是输出:
                foreach (KeyValuePair<string, List<Car>> pair in carDict)
                {
                    Console.WriteLine(pair.Key);
                    pair.Value.ForEach(x => Console.WriteLine(@"ID={0}, Name='{1}',OtherName='{2}'", x.ID, x.Name, x.OtherName));
                    Console.WriteLine();
                }
    
                Console.ReadKey();
            }

    字典按value排序

      Dictionary<string, int> dic = new Dictionary<string, int>();
               dic.Add("小明", 80);
                dic.Add("小李", 90);
                dic.Add("小王", 59);
                var list = dic.OrderBy(s => s.Value);

    List排序

    List 排序

    Sort
    OrderBy

    参考:

  • 相关阅读:
    window 编译lua 5.3
    邮件服务器软件
    mkyaffs2image 生成不了120M的镜像文件的解决方法
    C static struct
    uboot 如何向内核传递参数
    linux 链接理解
    snmp 协议之理解
    交叉编译知识点总结
    回滚原理 Since database connections are thread-local, this is thread-safe.
    REST 架构的替代方案 为什么说GraphQL是API的未来?
  • 原文地址:https://www.cnblogs.com/xinyf/p/10148659.html
Copyright © 2011-2022 走看看