根据字符串位置(C#)对字符串数组进行排序

时间:2012-11-16 13:48:40

标签: c# arrays string sorting position

我想知道如何根据特定的字符串位置对字符串[]的项进行排序。例如,我想通过子串“ - ”

对以下数组进行排序

输入:{xx - c,xxxxx - b,yyy - a,mlllll - d}

预期输出:{yyy - a,xxxxx - b,xx - c,mlllll - d}

到目前为止我所拥有的是:

public string[] SortByStringPos(string[] arr, string str, bool ascending)
{
    if (ascending)
    {
        var result = from s in arr
                     where s.Length >= s.IndexOf(str)
                     orderby s[s.IndexOf(str)] ascending
                     select s;

        return result.ToArray();
    }
    else
    {
        var result = from s in arr
                     where s.Length >= s.IndexOf(str)
                     orderby s[s.IndexOf(str)] descending
                     select s;

        return result.ToArray();
    }
}

有人可以给我一个提示......?

4 个答案:

答案 0 :(得分:3)

orderby x=>x.Substring(x.LastIndexOf('-'))

我猜

所以你需要以通常的方式订购它,然后你可以使用它,比如orderBy .... thenBy

答案 1 :(得分:3)

为了获得更好的性能和设计,我建议您使用:

    public void SortByStringPos(string[] arr, string str, bool ascending)
    {
        Array.Sort(arr, new MyStrComparer("-", ascending));
    }

    class MyStrComparer : Comparer<string>
    {
        string delimiter;
        bool isAscending;

        public MyStrComparer(string aStr, bool ascending)
        {
            delimiter = aStr;
            isAscending = ascending;
        }

        public override int Compare(string x, string y)
        {
            var r = GetMySubstring(x).CompareTo(GetMySubstring(y));
            return isAscending ? r : -r;
        }

        string GetMySubstring(string str)
        {
            return str.IndexOf(delimiter) != -1 ? str.Substring(str.LastIndexOf(delimiter)) : string.Empty;
        }

    }

您还可以删除SortByStringPos方法,然后从代码中的任意位置调用Array.Sort(arr, new MyStrComparer("-", ascending));

答案 2 :(得分:2)

static void Main()
{
    var input = new[] { "xx - c", "xx - b", "yy - a", "ml - d", };
    var delimeter = "-";
    var isAscending = true;

    var res = Sort(input, delimeter, isAscending);
}

static string[] Sort(string[] input, string delimeter, bool isAscending)
{
    var withDelimeter = input.Where(p => p.Contains(delimeter));
    var withoutDelimeter = input.Except(withDelimeter);

    Func<string, string> selector = p => p.Substring(p.IndexOf(delimeter));

    return
        (
            isAscending

                ? withDelimeter.OrderBy(selector)
                    .Concat(withoutDelimeter.OrderBy(p => p))

                : withoutDelimeter.OrderByDescending(p => p)
                    .Concat(withDelimeter.OrderByDescending(selector))
        )
        .ToArray();
}

答案 3 :(得分:0)

使用Substring获取字符串的最后一部分。 LINQ查询可以逐步构建。这减少了代码重复(= DRY原则,不要重复自己):

var query = arr.Where(s => s.Contains(str));
Func<string,string> sortExpr = s => s.Substring(s.IndexOf(str));
if (ascending) {
    query = query.OrderBy(sortExpr);
} else {
    query = query.OrderByDescending(sortExpr);
}
return query.ToArray();