我有一系列品牌,它们返回一个IEnumerable,并按照第一个字母对品牌进行分组。
@{
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>
}
呈现以下内容:
但是如果没有品牌以例如字母B,我怎么能总是呈现字母A-Z?我可以以某种方式加入一个带有字母属性的数组吗?
char[] letterArray = "ABCDEFGHIJKLMNOPQRSTUVWXYZÆØÅ".ToCharArray();
此外,我可以将任何品牌以&#34; 0-9&#34; -group中的数字开头?
答案 0 :(得分:2)
这样的事情怎么样?
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>
}