c# - Group items in collection by first letter -
i have collection of brands, returns ienumerable , have grouped brands first letter.
@{ var brands = service.getbrands(); <div class="list"> @foreach (var brand in brands.groupby(x => x.substring(0, 1).toupper(), (alphabet, sublist) => new { alphabet = alphabet, sublist = sublist.orderby(x => x).tolist() }).orderby(x => x.alphabet)) { <h4 class="letter">@brand.alphabet</h4> <div class="row"> @foreach (var item in brand.sublist) { <div class="brand col-md-3"> <div class="brand__title">@item</div> </div> } </div> } </div> }
which render following:
but in case no brands starts e.g. letter b, how can render letters a-z? can somehow join array alphabet property?
char[] letterarray = "abcdefghijklmnopqrstuvwxyzÆØÅ".tochararray();
furthermore can group brands starting number in "0-9"-group?
what this?
char[] alphabet = "abcdefghijklmnopqrstuvwxyz".tochararray(); var brands = service.getbrands(); var numberbrands = brands.where(x => char.isdigit(x.first())); <h4 class="letter">0-9<h4> <div class="row"> @foreach(var brand in numberbrands){ <div class="brand col-md-3"> <div class="brand__title">@brand</div> </div> } </div> foreach(var letter in alphabet){ var subbrands = brands.where(x => x.startswith(letter.tostring(), stringcomparison.ordinalignorecase)) .orderby(x => x); <h4 class="letter">@letter<h4> <div class="row"> @foreach(var brand in subbrands){ <div class="brand col-md-3"> <div class="brand__title">@brand</div> </div> } </div> }
Comments
Post a Comment