簡體   English   中英

使用List.Sort()時忽略空白

[英]Ignoring white space when using List.Sort()

我需要從文本文件中提取數據,對其進行排序,然后將舊數據與新排序的數據一起保存。 這是文本文件的格式:

Dog

Cow

Sheep

如果我將文本讀入列表,然后調用sort方法,則會得到以下信息:

""
""
""
Cow
Dog
Sheep

那不是我想要的 是否有一種方法可以讓.Sort()忽略空格,還是我應該以不同的方式處理此問題?

編輯當我保存回文件時,我需要在其中有空行。 輸出應為

Cow 

Dog

Sheep 

使用Linq。 以下應該工作:

string[] myText = File.RealAllLines("yourfile.txt");
var sortedWithoutEmptyLines = myText
     .Where(t=> !string.IsNullOrEmpty(t))
     .OrderBy(s=>s)
     .Select(i => string.Concat(i, Environment.NewLine)); //Adding extra linebreak as asked
File.WriteAllLines("yourfile.txt", sortedWithoutEmptyLines.ToArray());

我建議您改為僅使用非空格字符串構建另一個List並對其進行排序。 您不僅可以節省時間(如果每對“真實”字符串之間都留有空格,則基本上是無緣無故地對數據進行雙倍排序),而且編寫起來會容易得多。

string[] lines = File.ReadAllLines("yourInputFile.txt");
var outputData = lines
        .Where(line => !string.IsNullOrEmpty(line)) //remove empty lines
        .OrderBy(item => item)
        .Select(line => line + Environment.NewLine); //add them back in
File.WriteAllLines("yourOutputFile.txt", outputData.ToArray());

只需取出所有空行,進行排序,然后再放回去即可。

暫無
暫無

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

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