Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sort string based on substring with C#?

I have a string

string myStr = "*20@Apple#*10@Banana#*-5@Orange#*8@Cherries#";

I want an array that contains only fruit names from this string, but it should be sorted based on a value that is associated with it.

For example, in this string

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Apple => 20
Banana => 10
Orange => -5
Cherries => 8

I want this this array as a result

Orange, cherries, Banana, Apple

Thank You!

>Solution :

var input = "*20@Apple#*10@Banana#*-5@Orange#*8@Cherries#";

var result = input
      .Split(new []{'#','*' }, StringSplitOptions.RemoveEmptyEntries)
      .Select(x => x.Split('@'))
      .Select(x => (Rank : int.Parse(x[0]), Value : x[1]))
      .OrderBy(x => x.Rank)
      .Select(x => x.Value)
      .ToArray();

Console.WriteLine(string.Join(", ",result));

Output

Orange, Cherries, Banana, Apple
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading