Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort the file txt line 5000000?

Tags:

c#

sorting

i've got a disordered file with 500000 line which its information and date are like the following :

for instance          desired Result
------------          ---------------      
 723,80                1,4   
 14,50                 1,5 
 723,2                 10,8
 1,5                   14,50 
 10,8                  723,2 
 1,4                   723,80       

Now how can i implement such a thing ?

I've tried the sortedList and sorteddictionary methods but there is no way for implemeting a new value in the list because there are some repetative values in the list. I'd appreciate it if u suggest the best possible method .

One more thing , i've seen this question but this one uses the class while i go with File!

C# List<> Sort by x then y

like image 223
object json Avatar asked Dec 18 '13 14:12

object json


2 Answers

var result = File.ReadAllLines("...filepath...")
                 .Select(line => line.Split(','))
                 .Select(parts => new
                 {
                     V1 = int.Parse(parts[0]),
                     V2 = int.Parse(parts[1])
                 })
                 .OrderBy(v => v.V1)
                 .ThenBy(v => v.V2)
                 .ToList();

Duplicates will be handled properly by default. If you want to remove them, add .Distinct() somewhere, for example after ReadAllLines.

like image 87
Konrad Kokosa Avatar answered Sep 29 '22 07:09

Konrad Kokosa


You need to parse the file into an object defined by a class. Once it's in the object, you can start to sort it.

public class myObject
{
    public int x { get; set; }
    public int y { get; set; }
}

Now once you get the file parsed into a list of objects, you should be able to do something like the following:

var myList = new List<myObject>(); //obviously, you should have parsed the file into the list.
var sortedList = myList.OrderBy(l => l.x).ThenBy(l => l.y).ToList();
like image 23
Joe Brunscheon Avatar answered Sep 29 '22 07:09

Joe Brunscheon