6

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

Community
  • 1
  • 1
object json
  • 615
  • 1
  • 8
  • 20

3 Answers3

12
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.

Konrad Kokosa
  • 16,563
  • 2
  • 36
  • 58
2

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();
Joe Brunscheon
  • 1,949
  • 20
  • 21
2

First, sort each row so that they are in the correct order (e.g [723,80] - > [80,723]

Then sort all rows using a comparison something like this:

int Compare(Tuple<int,int> lhs, Tuple<int,int> rhs)
{
  int res = lhs.Item1.CompareTo(rhs.Item1)
  if(res == 0) res=lhs.Item2.CompareTo(rhs.Item2);

  return res;
}
Sean
  • 60,939
  • 11
  • 97
  • 136