如何按相同标准对2个列表进行排序? [英] How do I sort 2 lists by the same criteria?

查看:48
本文介绍了如何按相同标准对2个列表进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public void sort() 
{
    datelist = new List<DateTime>(rdate);   //timedates
    intlist = new List <Int>(rint);         //integers

    datelist.Sort((a, b) => a.CompareTo(b)); //sorts the dates ascending(I think)
}

我有两个初始数组;这些按索引号匹配.我已将它们转换为列表以便对其进行排序.我如何以与日期列表完全相同的方式对整数列表进行排序?谢谢.

I have two initial arrays; these match by index number. I have converted these to lists in order to sort them. How would I sort intlist in exactly the same way as the datelist? Thanks.

推荐答案

假设您可以使用linq(.net 3.5 +),则可以执行以下操作.

Assuming you have linq at your disposal (.net 3.5 +) you can do the following.

// Define your collections
var dates = new[]
                {
                    new DateTime(2012, 1, 1), new DateTime(2012, 1, 2), new DateTime(2012, 1, 5),
                    new DateTime(2012, 1, 3)
                };
var ints = new[] {1,2,4,3};

var result = dates
    .Select((d, i) => new {Date = d, Int = ints[i]}) // This joins the arrays based on index
    .OrderBy(o => o.Date) // Sort by whatever field you want
    .ToArray(); // Return the results an array

// Extract just the dates
dates = result.Select(o => o.Date).ToArray();
// Extract just the ints
ints = result.Select(o => o.Int).ToArray();

这篇关于如何按相同标准对2个列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆