簡體   English   中英

對字符串進行多級排序

[英]Multi-level sorting on strings

這是我擁有的原始數據:

Sana Paden,1098,64228,46285,2/15/2011
Ardelle Mahr,1242,85663,33218,3/25/2011
Joel Fountain,1335,10951,50866,5/2/2011
Ashely Vierra,1349,5379,87475,6/9/2011
Amado Loiacono,1406,62789,38490,7/17/2011
Joycelyn Dolezal,1653,14720,13638,8/24/2011
Alyse Braunstein,1657,69455,52871,10/1/2011
Cheri Ravenscroft,1734,55431,58460,11/8/2011

我使用帶嵌套Streamwriter的Filestream首先確定文件中有多少行,然后創建2個long數組,這些數組使我可以看到文件中每一行的開頭。 代碼如下:

using (FileStream fs = new FileStream(@"C:\SourceDatatoedit.csv", FileMode.Open, FileAccess.Read))
{
    fs.Seek(offset, SeekOrigin.Begin);
    StreamReader sr = new StreamReader(fs);
    {
        while (!sr.EndOfStream && fs.CanRead)
        {
            streamsample = sr.ReadLine();
            numoflines++;

        }// end while block
    }//end stream sr block

    long[] dataArray = new long[numoflines];
    fs.Seek(offset, SeekOrigin.Begin);
    StreamReader dr = new StreamReader(fs);
    {
        numoflines = 0;
        streamsample = "";

        while (!dr.EndOfStream && fs.CanRead)
        {
            streamsample = dr.ReadLine();
            //pointers.Add(numoflines.ToString());
            dataArray[numoflines] = offset;
            offset += streamsample.Length - 1;
            numoflines++;
        }// end while

一個字符串包含名稱,ID,貸款金額,付款金額和付款日期。 我有一種方法可以返回還款額,方法是從貸款額中減去還款額,然后將其除以100,得到美元和美分的價值。

完成此操作后,我想按日期,名稱,然后最后是負數順序對我的信息進行排序。 我知道我可以創建一個貸款類,然后創建一個貸款對象列表,並針對該集合運行Linq for Objects查詢以獲取此內容,但是我試圖在不使用Linq的情況下執行此操作。...有什么建議嗎?

根據您代碼的上下文,通過引入自定義類/業務對象可以獲得許多好處。 它將幫助您在代碼中很好地分離關注點,從而轉向更易於管理和測試的代碼。 您可以實現IComparable接口,以便可以對類型為List的集合調用自定義Sort。

我知道您提到過不要使用LINQ。 但是,您可以在此代碼行中使用一行代碼:

 using (FileStream fs = new FileStream(@"C:\SourceDatatoedit.csv", FileMode.Open,       FileAccess.Read))
{
  fs.Seek(offset, SeekOrigin.Begin);
  StreamReader sr = new StreamReader(fs);
  {
    while (!sr.EndOfStream && fs.CanRead)
    {
        streamsample = sr.ReadLine();
        numoflines++;

    }// end while block
  }//end stream sr block
}

對於這一行代碼,如下所示:

int numoflines = File.ReadLines("SourceDatatoedit.csv").
    Select(line => line.Split(',')).ToList().Count;

或者,您甚至可以像這樣獲得List

var lines = File.ReadLines("SourceDatatoedit.csv").
    Select(line => line.Split(',')).ToList();

然后得到行數

 numoflines = lines.Count;

然后繼續執行您喜歡的代碼:

  long[] dataArray = new long[numoflines];
fs.Seek(offset, SeekOrigin.Begin);
StreamReader dr = new StreamReader(fs);
{
    numoflines = 0;
    streamsample = "";

    while (!dr.EndOfStream && fs.CanRead)
    {
        streamsample = dr.ReadLine();
        //pointers.Add(numoflines.ToString());
        dataArray[numoflines] = offset;
        offset += streamsample.Length - 1;
        numoflines++;
    }// end while

或者只是使用上面獲得的List並像上面建議的那樣使用Isparqua創建一個IComparable實現。

暫無
暫無

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

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