我有一个数据集,当前生成的输出如下:
代码: 第 1 部分: View -
@foreach (var dt in Model.PlaceList) {
<tr class="Gap">
<td>
<div class="col-sm-12">
<h3>@dt.PlaceName</h3><br />
<span>@dt.OpenTimings</span><br />
<span>@dt.Slot</span><br />
<span>@dt.ActivityName</span><br />
<span>@dt.Address</span><br />
</div>
</td>
</tr>
}
第 2 部分:从数据库中检索数据
var gPlaceList = (from l in _appdb.GetPlaceDetails
select new GetListPlaces {
PlaceName = l.PlaceName,
OpenTimings = l.OpenTimings,
Slot = l.Slot,
Activity = l.Activity,
Address = l.Address
}).ToList();
第 3 部分:用于填充条目的数据结构
public partial class GetListPlaces {
public string PlaceName { get; set; }
public string OpenTimings { get; set; }
public string Slot { get; set; }
public string Activity { get; set; }
public string Address { get; set; }
}
当查看一个 Place 的输出结果时,我们得到的数据组如下所示:
当前输出:
Place Name Open Timings Slot1 Activity Address Place Name Open Timings Slot2 Activity Address Place Name Open Timings Slot3 Activity Address Place Name Open Timings Slot4 Activity Address Place Name Open Timings Slot5 Activity Address
对于其他 4 列匹配的所有结果,我们希望将结果合并为如下所示。
预期输出:
Place Name Open Timings Slot1, Slot2, Slot3, Slot4, Slot5 Activity Address
这里的数据只是一个示例。我们网站上的实际输出有数千个结果,像这样合并数据将有助于我们减少显示区域并减少数据重复。
最佳答案
将您的数据分组并使用字符串扩展方法“Join”以逗号分隔显示它
@foreach (var dt in Model.PlaceList.GroupBy(x=> new { x.PlaceName, x.OpenTimings, x.ActivityName, x.Address }))
{
<tr class="Gap">
<td>
<div class="col-sm-12">
<h3>@dt.Key.PlaceName</h3><br />
<span>@dt.Key.OpenTimings</span><br />
<span>@string.Join(",", dt.ToList().Select(x=>x.SlotNo))</span><br />
<span>@dt.Key.ActivityName</span><br />
<span>@dt.Key.Address</span><br />
</div>
</td>
</tr>
}
关于c# - 当 ASP.net MVC Razor 中的其他属性相同时重构循环以合并一个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45035819/