Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 排序多个列表_C#_Sorting - Fatal编程技术网

C# 排序多个列表

C# 排序多个列表,c#,sorting,C#,Sorting,我有3个列表,包括:索引、姓名、年龄 例如: List<int> indexList = new List<int>(); indexList.Add(3); indexList.Add(1); indexList.Add(2); List<string> nameList = new List<string>(); nameList.Add("John"); nameList.Add("Mary"); nameList.Add("Jane");

我有3个列表,包括:索引、姓名、年龄

例如:

List<int> indexList = new List<int>();
indexList.Add(3);
indexList.Add(1);
indexList.Add(2);
List<string> nameList = new List<string>();
nameList.Add("John");
nameList.Add("Mary");
nameList.Add("Jane");
List<int> ageList = new List<int>();
ageList.Add(16);
ageList.Add(17);
ageList.Add(18);
List indexList=new List();
添加索引列表(3);
添加索引列表(1);
增加(2);
列表名称列表=新列表();
姓名列表。添加(“约翰”);
姓名列表。添加(“玛丽”);
姓名列表。添加(“简”);
List ageList=新列表();
增列(16);
增列(17);
增列(18);
我现在必须根据索引列表对所有3个列表进行排序


如何在对其他两个列表进行排序时,将.sort()用于indexList

您看得不对。创建自定义类:

class Person
{
     public int Index { get; set; }
     public string Name{ get; set; }
     public int Age{ get; set; }
}
然后,借助
System.Linq
命名空间中的
OrderBy
方法对
列表进行排序:

List<Person> myList = new List<Person>() {
    new Person { Index = 1, Name = "John", Age = 16 };
    new Person { Index = 2, Name = "James", Age = 19 };
}
...

var ordered = myList.OrderBy(x => x.Index);
List myList=new List(){
新人{Index=1,Name=“John”,年龄=16};
新人{Index=2,Name=“James”,年龄=19};
}
...
var ordered=myList.OrderBy(x=>x.Index);

此外,您还可以阅读您的反模式。

法哈德的回答是正确的,应该被接受。但如果您确实必须以这种方式对三个相关列表进行排序,则可以使用和排序方式:

var joined = indexList.Zip(
        nameList.Zip(ageList, (n, a) => new { Name = n, Age = a }), 
            (ix, x) => new { Index = ix, x.Age, x.Name })
        .OrderBy(x => x.Index);
indexList = joined.Select(x => x.Index).ToList();
nameList = joined.Select(x => x.Name).ToList();
ageList = joined.Select(x => x.Age).ToList();

之后,所有对象都按索引列表中的值排序。

是否有任何理由将这些对象作为不同的相关对象列表,而不是将它们存储在一个类中,并将其作为属性?制作一个包含名称和年龄的
类(如果确实需要,还可以使用“索引”),然后使用
.OrderBy
.Dictionary/SortedList+匿名类将它们排序在一起?我已经编辑了你的标题。请参阅“”,其中的共识是“不,他们不应该”。另请参阅[帮助/标记]。@Aron,谢谢。我用那篇文章的链接更新了我的答案。