简体   繁体   中英

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

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

I want this this array as a result

Orange, cherries, Banana, Apple

Thank You!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM