c# - 使用 Linq 获取不同的属性
问题描述
我有一个对象列表,我必须在其中显示不同的属性,列表如下:
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
or解决它的任何更好的主意Linq
)
aLst = db.Questions.DistinctBy(p => new { p.QuestionId, p.QuestionName, p.Options }).ToList();
解决方案
@foreach(var item in Model.GroupBy(x=> x.QuestionId))
{
<div class="heading">
<div class="h2Val">
@item.Key
</div>
<div>@item.FirstOrDefault()?.QuestionName</div>
@foreach(var item2 in item.Select(x=>x.Options).ToList())
{
<div class="heading2">
<div>
<input type = "checkbox" class="cbCheck" value="@item2" />@item2
</div>
</div>
}
<div>
<input type = "button" class="btn" value="Get Value" />
</div>
</div>
}
推荐阅读
- django - localhost 未从 pgadmin 表中获取数据
- haxe - 如何从宏/评估中获取“haxe.exe”的路径?
- sql - 如何在 SQL 中修改/重命名数据库名称?
- scala - 为什么 spark 总是尝试连接到 localhost:9042?
- c++ - C ++如何强制转换动态派生类
- jquery - 在视口中向下滚动元素时隐藏(淡入淡出)元素
- javascript - 获取一组背景图像以供以后保存,然后在它们和背景颜色之间悬停切换
- c++ - 模板下标运算符重载
- python - add_form 和 form 的区别
- java - 我不知道如何通过 windows 命令提示符输入