C# 对List或Map 进行排序

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp2
{
    public class MyInfo
    {
        public MyInfo(string name, int level, int age)
        {
            this.name = name;
            this.level = level;
            this.age = age;
        }
        public string name;
        public int level;
        public int age;
    }
    public class Program
    {
        public static List<MyInfo> myList = new List<MyInfo>();
        public static Dictionary<int, MyInfo> myDic = new Dictionary<int, MyInfo>();

        static void Main(string[] args)
        {
            myList.Add(new MyInfo("A", 2, 9));
            myList.Add(new MyInfo("C", 8, 6));
            myList.Add(new MyInfo("B", 6, 7));

            myDic.Add(1, new MyInfo("A", 2, 9));
            myDic.Add(2, new MyInfo("C", 8, 6));
            myDic.Add(3, new MyInfo("B", 6, 7));


            // 按年龄排序
            myList.Sort((x, y) => { return x.age.CompareTo(y.age); });
            myDic = myDic.OrderBy(s => s.Value.age).ToDictionary(pair => pair.Key, pair => pair.Value);

            // 查询
            var query = (from s in myDic
                        where s.Value.name == "A"
                        select s).ToDictionary(pair => pair.Key, pair => pair.Value);

            Console.WriteLine("============= List: ");
            foreach (var item in myList)
            {
                Console.WriteLine(item.name + " " + item.level + " " + item.age);
            }

            Console.WriteLine("============= Dic: ");
            foreach (var item in myDic)
            {
                Console.WriteLine(item.Key + " " + item.Value.name + " " + item.Value.level + " " + item.Value.age);
            }

            Console.WriteLine("============= 查询结果Dic2: ");
            foreach (var item in query)
            {
                Console.WriteLine(item.Key + " " + item.Value.name + " " + item.Value.level + " " + item.Value.age);
            }


            Console.WriteLine("============= Index: ");
            // 获取字典对应的索引
            var item1 = Array.IndexOf( myDic.Keys.ToArray(), 2);
            Console.WriteLine(item1);

            Console.ReadLine();
        }
    }
}


  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值