【发布时间】:2020-11-04 04:31:32
【问题描述】:
我有一个对象列表,我必须在其中显示不同的属性,列表如下:
public class Questions
{
public Nullable<int> QuestionId { get; set; }
public string QuestionName { get; set; }
public string Options { get; set; }
}
public List<Questions> GetLst()
{
List<Questions> aLst = new List<Questions>()
{
new Questions() { QuestionId = 1, QuestionName = "What is the capital of England?", Options = "London" },
new Questions() { QuestionId = 1, QuestionName = "What is the capital of Engand?", Options = "Jakarta" },
new Questions() { QuestionId = 2, QuestionName = "Who invented computer?", Options = "Thomas Edison" },
new Questions() { QuestionId = 2, QuestionName = "Who invented computer?", Options = "Charles Babbage" },
};
return aLst;
}
因此可以看出,列表中有重复的属性值,如QuestionId和QuestionName。所以在前端,我使用Razor 来显示列表,并且简单地将循环迭代为给定对象的数量。
@foreach (var item in Model.Distinct())
{
<div class="heading">
<div class="h2Val">
@item.QuestionId
</div>
<div>@item.QuestionName</div>
@foreach (var item2 in Model.Where(c => c.QuestionId == item.QuestionId))
{
<div class="heading2">
<div>
<input type="checkbox" class="cbCheck" value="@item2.Options" />@item2.Options
</div>
</div>
}
<div>
<input type="button" class="btn" value="Get Value" />
</div>
</div>
}
所以我的预期输出如下:
1
What's the capital of England?
Option 1: London
Option 2: Jakarta
我现在得到了什么:
1
What's the capital of England?
Option 1: London
1
What's the capital of England?
Option 2: Jakarta
我尝试了这样的方法来区分属性值,如下所示,但它根本没有帮助:(使用Razor 或Linq 解决它的更好主意)
aLst = db.Questions.DistinctBy(p => new { p.QuestionId, p.QuestionName, p.Options }).ToList();
【问题讨论】:
-
在此期间,如果有熟悉
jQuery并有时间的人,请到这个小提琴-jsfiddle.net/vrog5pbn。我没有将它作为单独的线程发布,它似乎是一个需要解决的简单问题。 -
即使在
DistinctBy(p => new { p.QuestionId, p.QuestionName, p.Options })下,问题也是不同的——它们有不同的选项。这里的实际问题是您的数据结构不适合手头的任务。应该是{ QuestionId = 1, QuestionName = "What is the capital of England?", Options = new [] {"London", "Jakarta" } } -
另外,请单独发布您的 jQuery 问题。
标签: c# jquery asp.net-mvc linq razor