Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# csv sorting a list using third columns

Tags:

c#

winforms

I have a program that opens a CSV file using StreamReader and creates a table with 4 columns and rows for however many rows are in the CSV file. This works correctly as is creating the output of:

Item Code, Item Description, Current Count, On Order

A0001, Toy Car, 4, Yes

A0002, Toy Truck, 1, No

I save all the data from the CSV file in a global list without splitting each line. When I am creating the table I split the lines using "Split(',')", which works as needed at the time. However I am unsure how to reorder the whole list using the Current Count column from largest to smallest. I have tried the following but it give an error on the Split(',').

public static class Globals
{
    public static List<string> items = new List<string>();
}
private void createTableWithOrder(int order)
{
    for (int i = 0; i < Globals.items.; i++)
    {
         var values = Globals.items[i].Split(',');

         if (order == 1)
         {
              values = Globals.items[i].OrderBy(itemDesc => itemDesc.Split(',')).ToList();
         }
    }
}

The Error given is below:

'char' does not contain a definition for 'Split' and no extension method 'Split' accepting a first argument of type 'char' could be found (are you missing a using directive or an assembly reference?)

like image 920
Matt Wilkinson Avatar asked Mar 21 '26 02:03

Matt Wilkinson


1 Answers

The OrderBy call is working on all characters in the string at Globals.items[i]. That is why you're seeing the current error. In order to sort the entire collection the order by needs to be made on the list as a whole, e.g:

var values = Globals.items.Select(line => line.Split(',')); // Select columns for all rows
var orderedListOfValues = values
    .OrderByDescending(cols => int.TryParse(cols[2].Trim(), out var order) ? order : int.MaxValue); // Sort  by count as an integer

Note that in the above example sorting on non-numeric values (e.g. heading) will use the maximum value of an integer. Depending on the expected outcome, these results can then be merged back into a list of strings for presentation:

var orderedItems = string.Join(",", orderedListOfValues)

Cheers!

like image 101
Patrick Avatar answered Mar 22 '26 16:03

Patrick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!