簡體   English   中英

如何創建Alphabet和Number的字符串組合系列?

[英]How to create series of string combination of Alphabet and Number?

我有一個數據列表集合,例如:

List<String> Dummy = new List<String>()
{
  "1001A",
  "1003A",
  "1002B",
  "1002A",
  "1003B",
  "1001B",
  "1003C",
  "1002C",
  "1001C",
};

我想把這個數據列表整理成一系列。 主要系列將重點關注Alphabet(字符串的最后一個字符),子系列將基於左邊的數字。 輸出將是這樣的:

1001A
1002A
1003A
1001B
1002B
1003B
1001C
1002C
1003C

除了上面的示例之外,我已經只有一系列數字的功能代碼。 感謝閱讀我的帖子。

 var result = Dummy
              .OrderBy(p => p[p.Length - 1])
              .ThenBy(p => p.Substring(0, p.Length - 1));

這將首先按字符串的最后一個字符排序,然后按字符串的最后一個字符除外。

如果所有字符串都具有相同的長度,您也可以將最后一部分保留在.ThenBy(p => p) ,因為字符串已經按最后一個字符排序。 如果字符串長度不同,則需要在我的代碼中使用子字符串。

如果字符串可能具有不同的長度,則需要以下內容。

var result = data.OrderBy(d => d[d.Length - 1])
                 .ThenBy(d => int.Parse(d.Substring(0, d.Length - 1])));

您當然需要防止可能使用錯誤數據解析異常。

這假設你想要“200A”來到“1000A”之前。

版本a) (最快)

使用內置的Sort方法(就地排序),使用自定義Comparision委托/ lambda

 dummy.Sort((s1, s2) =>
 {
      // TODO: Handle null values, now supposing s1 and s2 are not null
      // TODO: Handle variable length if needed. Supposing fixed 4+1 data 
      var result = s1[4].CompareTo(s2[4]);
      if (result != 0)
      {
          return result;
      }
      return s1.Substring(0, 4).CompareTo(s2.Substring(0, 4));
  });

要重用Comparision,您可以將其編寫為靜態方法而不是內聯lambda,但是我建議這樣做以實現IComparator。 (Sort方法有一個接受IComparator的重載)

版本b):

使用LINQ:

// TODO: Handle variable length if needed, supposing fixed 4+1 data structure:
var orderedList = dummy.OrderBy(s => s[4]).ThenBy(s => s.SubString(0,4).ToList();

基於分組的解決方案:

var res = Dummy.GroupBy(str => str.Last()).OrderBy(g => g.Key)
               .SelectMany(g => g.OrderBy(str => str.Substring(0, str.Length - 1)))
               .ToList();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM