我有一个详细信息页面,可以从多个表中引入数据。我想让它带回一个表的完整列表,然后根据视图的不同部分中的类别分割出列表。我没有问题带回完整的清单:
LocalService.java
带来了Apple,Apple,Apple,Apple,Orange,Orange,Lime等产品。当我尝试将其分区时,我想要的是:
1x Lime等。
var query = string.Format("Select C.* from Cards C Left Join CardDecks CD ON CD.CardID = C.CardID Where DeckID = {0}", id);
var cardlist = db.Cards.SqlQuery(query).ToList();
我的视图模型:
var creaturelist = " ";
var list = creatures.Select(t => t.Title).ToList();
var section = list.GroupBy(c => c, (a, b) => new { Title = a, Count = b.Count() });
foreach (var item in section)
{
creaturelist = string.Format("{0}x {1}", item.Count, item.Title);
}
var vm = new ViewDeck();
vm.Deck = deck;
vm.CardList = cardlist;
vm.Creatures = creaturelist;
return View(vm);
有问题的观点部分:
public class ViewDeck
{
public Deck Deck { get; set; }
public Card Cards { get; set; }
public CardDeck CardDecks { get; set; }
public IList<Card> CardList { get; set; }
public dynamic Creatures { get; set; }
}
我得到的结果是重复最后一次计数加上标题,如1x Lime重复,因为标题中存在多个字符。我不明白为什么它会贯穿标题的每个字符,而不仅仅是抓住标题的整个价值。
答案 0 :(得分:3)
您必须在模型中将Creatures
定义为列表而不是string
,然后通过在循环中添加项来生成列表:
var creaturelist = new List<string>();
var list = creatures.Select(t => t.Title).ToList();
var section = list.GroupBy(c => c, (a, b) => new { Title = a, Count = b.Count() });
foreach (var item in section)
{
creaturelist.Add(string.Format("{0}x {1}", item.Count, item.Title));
}
var vm = new ViewDeck();
vm.Deck = deck;
vm.CardList = cardlist;
vm.Creatures = creaturelist;
return View(vm);
并在视图中
CREATURES<br />
@foreach (var item in Model.Creatures)
{
@item<br />
}
你可以不带循环制作列表:
var creaturelist =
list.GroupBy(c => c, (a, b) => string.Format("{0}x {1}", b.Count(), a)).ToList();