Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Linq - how to select top 5 rows from a List<string> splitting on the first value

Tags:

c#

select

linq

I probably worded this the wrong way, but I have a simple List that based on a split I want the greatest values from the first column.

Here is the code

   List<string> myString = new List<string>();
        myString.Add("100.02|apples|pears");
        myString.Add("22.02|apples|pears");
        myString.Add("99.02|apples|pears");
        myString.Add("88.02|apples|pears");
        myString.Add("77.02|apples|pears");
        myString.Add("66.02|apples|pears");

I'm basically splitting on | and then converting the first column to decimal. I want to get the greatest 5 rows to this would exclude 22.02. I've tried sorting and ordering but they dont work because the strings are differnt lengths.

Thanks!

like image 660
JL1 Avatar asked Nov 20 '25 05:11

JL1


1 Answers

This will work:

List<string> myString = new List<string>();
myString.Add("100.02|apples|pears");
myString.Add("22.02|apples|pears");
myString.Add("99.02|apples|pears");
myString.Add("88.02|apples|pears");
myString.Add("77.02|apples|pears");
myString.Add("66.02|apples|pears");

var res = myString.Select(s => new
{
    num = decimal.Parse(s.Split('|')[0]),
    str = s
}).OrderByDescending(g => g.num).Take(5).Select(s => s.str);
res.Dump();

No error checking whatsoever, but it gives you the result:

100.02|apples|pears
99.02|apples|pears
88.02|apples|pears
77.02|apples|pears
66.02|apples|pears

like image 196
Rob Avatar answered Nov 21 '25 20:11

Rob