【问题标题】:How to group a C# list when being displayed in html page在html页面中显示时如何对C#列表进行分组
【发布时间】:2022-12-07 16:46:12
【问题描述】:
string flowerList = string.Empty;
foreach (var flower in Plants.Where(x => x.Status == PlantStatus.Active))
{
    flowerList = string.IsNullOrWhiteSpace(flowerList)
                 ? "<li>" + flower.Colour + " " + flower.Priority + " " + flower.Category + "</li>"
                 : flowerList + "<li>" + flower.Colour + " " + flower.Priority + " " + flower.Category+ "</li>" ;
}

我有上面的代码在 html 页面中显示 C# 列表数据。我如何将 flower.Category 输出的 flowerList html 分组。

对于每个类别,我希望将 flower.Category 作为组标题,然后在其下列出相关记录。

【问题讨论】:

  • 您已经在使用 LINQ。你试过GroupBy操作了吗?不要将查询放在 foreach 子句中。已经很难读了。

标签: c# html


【解决方案1】:

该代码已经在使用 LINQ。 LINQ 中的分组由 GroupBy 运算符执行。不过,将查询放在 foreach 子句中并不是一个好主意,即使对于简单的查询也是如此。修改它变得更加困难。

此 sn-p 按类别分组,然后生成 HTML 字符串。尽管它使用 StringBuilder 来避免创建临时字符串,但它没有连接字符串。

var categories=Plants.Where(x => x.Status == PlantStatus.Active)
                 .GroupBy(x=>x.Category);

var builder=new StringBuilder("<ul>");
foreach(var plants in categories)
{
    foreach(var plant in plants)
    {
        builder.AppendFormat("<li>{0} {1} {2}</li>
", 
                           flower.Colour, 
                           flower.Priority, 
                           flower.Category);
    }
}
builder.AppendLine("</ul>");

var html=builder.ToString();

【讨论】:

    【解决方案2】:

    这是按 flower.Category 对输出进行分组的一种可能方法:

    string flowerList = string.Empty;
    
    // Group the flowers by category
    var flowerGroups = Plants
        .Where(x => x.Status == PlantStatus.Active)
        .GroupBy(x => x.Category);
    
    // Iterate over the groups and create the HTML output
    foreach (var group in flowerGroups)
    {
        // Create the header for the group
        flowerList += "<h3>" + group.Key + "</h3>";
    
        // Create a list of flowers in the group
        flowerList += "<ul>";
        foreach (var flower in group)
        {
            flowerList += "<li>" + flower.Colour + " " + flower.Priority + " " + flower.Category + "</li>";
        }
        flowerList += "</ul>";
    }
    

    此代码将首先按 flower.Category 对花进行分组,然后遍历这些组并为每个组创建一个标题,然后是该组中的花列表。最终结果将是一个包含 HTML 输出的字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-08
      • 1970-01-01
      • 2012-11-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多