Home > database >  How can I order values from a CSV highest to lowest
How can I order values from a CSV highest to lowest

Time:10-25

My goal is to take the values from a CSV file and sort them by highest to lowest using the column "cost basis"

Currently, my code looks like

I would appreciate any help you guys are able to provide.

{
class Program
{   
    static dynamic convertcsvtolists(string path)
    {
        using (var reader = new StreamReader(path))
        using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
        {
            var dynObj = csv.GetRecords<dynamic>().ToList();

            foreach (var d in dynObj)
            {
                var obj = d as System.Dynamic.ExpandoObject;

                if (obj != null)
                {
                    var keys = obj.Select(a => a.Key).ToList();
                    var values = obj.Select(a => a.Value).ToList();
                }
            }   return dynObj;
        }

    }

    static void Main(string[] args)
    {
        var transactions = convertcsvtolists(@"PathFile");
    
        Console.ReadLine();

    }
}

}

CodePudding user response:

If you can convert data in class like this as example:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public decimal CostBasis { get; set; }
}

Then you can use like this:

using (var csv = new CsvReader(textReader, configuration))
{
    var data = csv.GetRecords<Person>(); // this is a list
    
    // sort the data
    var sortedData = data.OrderBy(x => x.CostBasis).ToList();
}

CodePudding user response:

  1. Never name methods with lowercase letters :)
  2. Use dynamic when needed (never)
  3. Use / Learn LINQ, or maybe sort with your own algorithm :)
  •  Tags:  
  • c#
  • Related