基于另一个列表的C#排序列表 [英] C# Sort List Based on Another List

查看:85
本文介绍了基于另一个列表的C#排序列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多个List <>的类.它基本上是一个表,每个列都以List<>的形式存储.每列都不包含相同的类型.每个列表的长度也相同(元素数相同).

I have a class that has multiple List<> contained within it. Its basically a table stored with each column as a List<>. Each column does not contain the same type. Each list is also the same length (has the same number of elements).

例如:

我有3个List<>对象;一个列表,两个列表和三个列表.

I have 3 List<> objects; one List, two List, and three List.

//Not syntactically correct
List<DateTime> one = new List...{4/12/2010, 4/9/2006, 4/13/2008};
List<double> two = new List...{24.5, 56.2, 47.4};
List<string> three = new List...{"B", "K", "Z"};

我希望能够从最旧到最新对列表进行排序: 一个= {4/9/2006,4/13/2008,4/12/2010};

I want to be able to sort list one from oldest to newest: one = {4/9/2006, 4/13/2008, 4/12/2010};

为此,我将元素0移到了末尾.

So to do this I moved element 0 to the end.

然后,我想以相同的方式对列表2和列表3进行排序;将第一个移到最后一个.

I then want to sort list two and three the same way; moving the first to the last.

因此,当我对一个列表进行排序时,我希望其他列表中相应索引中的数据也根据对一个列表的排序方式进行更改.

So when I sort one list, I want the data in the corresponding index in the other lists to also change in accordance with how the one list is sorted.

我猜我必须以某种方式使IComparer重载,但是我觉得还有一个我没有意识到的捷径.

I'm guessing I have to overload IComparer somehow, but I feel like there's a shortcut I haven't realized.

推荐答案

我过去通过保存或创建单独的索引列表来处理此设计.您首先对索引列表进行排序,然后使用它对其他列表进行排序(或仅访问).您可以通过为索引列表创建自定义IComparer来实现.您在IComparer内部所做的是根据键列表中的索引进行比较.换句话说,您正在间接地对索引列表进行排序.像这样:

I've handled this design in the past by keeping or creating a separate index list. You first sort the index list, and then use it to sort (or just access) the other lists. You can do this by creating a custom IComparer for the index list. What you do inside that IComparer is to compare based on indexes into the key list. In other words, you are sorting the index list indirectly. Something like:

// This is the compare function for the separate *index* list.
int Compare (object x, object y)
{
  KeyList[(int) x].CompareTo(KeyList[(int) y])
}

因此,您正在根据键列表中的值对索引列表进行排序.然后,您可以使用该排序的键列表对其他列表进行重新排序.如果不清楚,我将在遇到情况后尝试添加一个更完整的示例.

So you are sorting the index list based on the values in the key list. Then you can use that sorted key list to re-order the other lists. If this is unclear, I'll try to add a more complete example when I get in a situation to post one.

这篇关于基于另一个列表的C#排序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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