按多列对C#中的锯齿状数组进行排序 [英] Sorting a jagged array in C# by multiple columns

查看:47
本文介绍了按多列对C#中的锯齿状数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有很多问题和答案,但都不适用于我的问题.我有一个锯齿状的数组,我想按数组b,c和d中的值排序:

I know there's been a lot of questions and answers but neither applies to my problem. I have a jagged array that I'd like to sort by the values in array b, c and d:

string[][] toBeSorted = new string[][] { a, b, c, d, e, f, g, h, i, j};

这仅按行"排序

toBeSorted = toBeSorted.OrderBy(inner => inner[2]).ToArray();

我尝试了 Array.Sort(c.ToArray(),b)和类似的方法,但是在进行多值排序的情况下,它们混合了整个选择

I have tried Array.Sort(c.ToArray(), b) and similar approaches but they mixed the whole selection in case of multiple valued sorting

现在,当我在 toBeSorted 中有"John","Smith","New York"等值时,我想让我的数组按城市",姓氏"排序,例如最后按数组 g 中的值排序.因此,值是a =名称,b =姓氏等.

So now when I have values in toBeSorted like "John", "Smith", "New York", etc. I'd like to have my array sorted by the "cities", "surnames" and for example by the values in array g at last. So the values are a = names, b = surnames, etc.

在我的情况下,我依赖.NET 3.5.

I am .NET 3.5 dependent in my scenario.

谢谢.

推荐答案

而不是使用 string [] [] ,其中内部数组中的每个项实际上代表数据创建的不同标记"适当的类,其属性为那些标签":

Instead of using a string[][] where each item in the inner array actually represents a different "tag" of data create a proper class with the properties being those "tags":

public class Person
{
    public string Name { get; set; }
    public string LastName { get; set; }
    public string City { get; set; }
}

然后:

var people = new List<Person>
{
    new Person { Name = "A", LastName = "1", City = "B" },
    new Person { Name = "B", LastName = "3", City = "B" },
    new Person { Name = "C", LastName = "2", City = "B" },
};

//Linq OrderBy:
var result = people.OrderBy(p => p.LastName);

//List Sort:
people.Sort((x, y) => string.Compare(x.LastName, y.LastName));

这篇关于按多列对C#中的锯齿状数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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