首页 > 解决方案 > 使用 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;
}

因此可以看出,在列表中有重复的属性值,如QuestionIdQuestionName。所以在前端,我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

我尝试了类似的方法来区分属性值,如下所示,但它根本没有帮助:(使用Razoror解决它的任何更好的主意Linq

aLst = db.Questions.DistinctBy(p => new { p.QuestionId, p.QuestionName, p.Options }).ToList(); 

标签: c#jqueryasp.net-mvclinqrazor

解决方案


 @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>
 }

推荐阅读