0

我在使用数组作为排序源按索引对列表进行排序时遇到问题。

假设我的班级有 5 条记录

class Program
{
    static void Main(string[] args)
    {
     int[] myInt {2,1,0,3,4}
     List<Tests> myTests = new List<Tests>; 

     //this part doesn't work

     for (int i = 0; i < 4; i++)
        {
         myInt[i] = myTests[i];
         }
     myTests.ForEach(i => Console.WriteLine("{0} {1}", i.id, i.myString));
    }
}

我的班级定义

class Tests
{
     public int iD {get; set;}
     public string myString {get; set;}

     public Tests (int iD, string myString)
    {
       this.iD = iD;
       this.myString = myString
    }
{

我想看到的出来

     record 2
     record 1
     record 0
     record 3
     record 4

我尝试对列表使用排序函数,但我找不到任何使用数组作为排序标准的示例,所以我有点迷路了。我感谢提供的任何帮助。

4

4 回答 4

2

在我的脑海中,这样的事情应该可以解决问题:

var sortedTests = myInt
    .Select((x,index) => new {test = myTests[x], sortIndex = index})
    .OrderBy(x => x.sortIndex)
    .Select(x => x.test)
    .ToList()

唔。事实上,使用 Linq-to-objects 会更容易一些:

var sortedTests = myInt
    .Select(x => myTests[x])
    .ToList();
于 2012-12-06T13:02:34.983 回答
0

您应该将 myTests 的值分配给另一个 List

List<Tests> newTests = new List<Tests>();
for (int i = 0; i < 4; i++)
{
    newTests.Add(myTests[myInt[i]]);
}
于 2012-12-06T13:03:28.150 回答
0

第一的:

myList[i]除非您在 position 中创建了列表项,否则您无法使用i

第二:

您没有调用Tests构造函数来创建新Tests对象

第三:

您分配给myInt[i]一个空的参考myTests[i]

你应该有类似的东西:

for (int i = 0; i < 4; i++) {

    myTests.Add(new Tests(i, "foo"))

}
于 2012-12-06T13:03:56.467 回答
0

您提供的代码有点模糊,所以我编造了几个不同的场景。
1.基于索引创建。
2.根据索引排序。

将其粘贴到您的 IDE 中,它将起作用。

 class Program
  {
    static void Main(string[] args)
    {
      int[] myInt = new[] { 2, 1, 0, 3, 4 };

      // there is nothing to sort at this time, but this is how I would make a new list matching your index....
      var myTests = (from x in myInt select new Tests(x, "whatever")).ToList();

      myTests.ForEach(i => Console.WriteLine("{0} {1}", i.iD, i.myString));


      // So assuming that you are starting with an unsorted list....
      // We create and priont one....
      myTests = new List<Tests>();
      for (int i = 0; i < myInt.Length; i++)
      {
        myTests.Add(new Tests(i, "number " + i));
      }

      Console.WriteLine("unsorted ==");
      myTests.ForEach(i => Console.WriteLine("{0} {1}", i.iD, i.myString));

      // And this will perform the sort based on your criteria.
      var sorted = (from x in myInt
                    from y in myTests
                    where y.iD == x
                    select y).ToList();

      // And output the results to prove it.
      Console.WriteLine("sorted ==");
      sorted.ForEach(i => Console.WriteLine("{0} {1}", i.iD, i.myString));

      Console.Read();
    }
  }
于 2012-12-06T13:27:47.683 回答