如何使用 Linq 对二维数组进行排序?

发布于 2024-12-12 06:02:21 字数 325 浏览 0 评论 0原文

我有一个二维字符串数组

string [] [] myArray;

,我想按其中一列对其进行排序。

所以数据可能是

{ "Apple", "2", "Bob" },
{ "Banana", "1", "Fred" }

,我想按这些列中的任何一个对它进行排序 - 我将有一个索引。

理想情况下,我想做类似 myArray.Sort(1);

我知道我可能必须使用自定义比较器。我认为这是一个有趣的学习机会。有人可以提供一些建议吗?

I have a 2d array of strings

string [] [] myArray;

and I want to sort it by one of the columns.

So the data might be

{ "Apple", "2", "Bob" },
{ "Banana", "1", "Fred" }

And I want to sort it by any of those columns - I'll have an index.

Ideally, I'd like to do something like myArray.Sort(1);

I understand I may have to use a custom comparer. I see this as an interesting learning opportunity. Can anyone offer some advice?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

世俗缘 2024-12-19 06:02:21
var myOrderedRows = myArray.OrderBy(row => row[columnIndex]);
var myOrderedRows = myArray.OrderBy(row => row[columnIndex]);
楠木可依 2024-12-19 06:02:21
Array.Sort(myArray, (p, q) => p[0].CompareTo(q[0]));

这将对数组进行排序(因此最后 myArray 将被排序)。相比之下,LINQ OrderBy 创建一个新的有序枚举,然后您可以将其转换为 ToArray

Array.Sort(myArray, (p, q) => p[0].CompareTo(q[0]));

This will order the array in place (so at the end myArray will be sorted). LINQ OrderBy by comparison creates a new ordered enumerable that then you can convert to a ToArray.

澉约 2024-12-19 06:02:21

你可以这样做......

IEnumerable<T> AsEnumerable(this T[,] arr) {
  for(int i = 0; i < arr.GetLength(0); i++)
    for(int j = 0; j < arr.GetLength(1); j++)
      yield return arr[i, j];
}

然后写例如:

int[,] data = // get data somwhere
// After 'AsEnumerable' you can use all standard LINQ operations
var res = data.AsEnumerable().OrderBy(n => n).Reverse();

you can do like this...

IEnumerable<T> AsEnumerable(this T[,] arr) {
  for(int i = 0; i < arr.GetLength(0); i++)
    for(int j = 0; j < arr.GetLength(1); j++)
      yield return arr[i, j];
}

And then write for example:

int[,] data = // get data somwhere
// After 'AsEnumerable' you can use all standard LINQ operations
var res = data.AsEnumerable().OrderBy(n => n).Reverse();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文