简体   繁体   中英

How to Group an array by lengths of 10, 0-10, 11-20, etc

I'm attempting to group an array of strings by their lengths, ie 1-10, 11-20, 21-30, then sort them using Linq/C#. I was thinking that I could loop through and do an if statement to break them up into separate arrays, then put them back together into one. This has a bad feel though - like Group By is a better option, but I haven't been able to figure out how exactly.

with helper range array, you can group list and then sort it

string[] list = new[] { "12345", "12", "12", "55", "12345", "1", "22", "333" };

var range = new[] { 2, 4, 5 };
var grouppedItems = list.GroupBy(s => range.First(i => i >= s.Length));
var sortedItems = grouppedItems.OrderBy(group => group.Key);

Some good ideas in the question's comments, Here I come with a solution where you would have a full control on each property while showing records on the view.

You can use desired length of interval you want, 10, 15, 20 whatever, also you will have min and max length in hand for each group to be used on view if you wanted to show the length range with each set.

string[] strings = new[] { "Taco Bell", "McDonalds", "Pizza Hut", "Wendys", "Dunkin' Donuts" };

int lengthRangeInterval = 10;

var groupsByLengthRange = strings.GroupBy(s => s.Length / lengthRangeInterval).Select(g =>
  new
  {
    MinLength = (g.Key * lengthRangeInterval) + 1,
    MaxLength = (g.Key * lengthRangeInterval) + lengthRangeInterval,
    Items = g.ToArray()
  }).OrderBy(g => g.MinLength).ToArray();

Not clear from the question exactly what you want to sort by. If you want to sort by the length, then here's a solution.

new[] { "nine char", "ten chars!", "13 characters", "14 characters!", "eight ch", "twentytwo!!!!!!!!!!!!!", "twentythree!!!!!!!!!!!!" }
.GroupBy( x => (x.Length - 1) / 10 )
.OrderBy(group => group.Key )
.Select( group => group.ToArray() );

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