Skip to main content
 首页 » 编程设计

c#之如何在组的开头和结尾处使用文本在 linq 中进行分组

2024年02月20日13jackei

我的主题数据如下所示:

010000 <- Top level header 
010100 A <- Sub level header 
010101 B <- Clickable item in the select list 
010102 C <- Clickable item in the select list 
010103 D <- Clickable item in the select list 
010200 E <- Sub level header 
010201 F <- Clickable item in the select list 
010202 G <- Clickable item in the select list 

目前我正在使用以下代码制作一个显示所有内容的选择列表:

var topics = contentService.Get(accountID + "06000").OrderBy(o => o.Order); 
foreach (Content topic in topics) { 
    txt += "<option value='" + topic.RowKey + "'>" + topic.Name + "</option>\n"; 
} 

有什么办法可以改变这个:

  • 顶级标题不是选择列表的一部分?换句话说,以“0000”结尾的每一行都不会放入主题变量中。
  • 子级标题在选择列表中显示为组。

这样的组:

<select> 
  <optgroup label="A"> 
      <option value="010101">B</option> 
      <option value="010102">C</option> 
      <option value="010103">D</option> 
  </optgroup> 
  <optgroup label="E"> 
      <option value="010201">F</option> 
      <option value="010202">G</option> 
  </optgroup> 
</select> 

我希望有人能提供帮助。我想也许我可以做限制,但我不知道如何进行开始和结束分组。

请您参考如下方法:

为了简化问题,我们假设您的主题在以下 List 中定义:

List<Tuple<string, string>> topics = new List<Tuple<string, string>> 
{ 
    Tuple.Create("010000", string.Empty), 
    Tuple.Create("010100", "A"), 
    Tuple.Create("010101", "B"), 
    Tuple.Create("010102", "C"), 
    Tuple.Create("010103", "D"), 
    Tuple.Create("010200", "E"), 
    Tuple.Create("010201", "F"), 
    Tuple.Create("010202", "G"), 
}; 

然后,您可以简单地遍历每个主题并逐步构建您的 HTML:

XElement select = new XElement("select"); 
XElement optGroup = null; 
 
foreach (var topic in topics) 
{ 
    // skip root topic 
    if (!topic.Item1.EndsWith("0000")) 
    { 
        // optgroup 
        if (topic.Item1.EndsWith("00")) 
        { 
            optGroup = new XElement("optgroup", new XAttribute("label", topic.Item2)); 
            select.Add(optGroup); 
        } 
        // option 
        else if (optGroup != null) 
        { 
            optGroup.Add(new XElement("option", new XAttribute("value", topic.Item1), new XText(topic.Item2))); 
        } 
    } 
} 
 
Console.WriteLine(select); 

您将获得以下控制台输出:

<select> 
    <optgroup label="A"> 
        <option value="010101">B</option> 
        <option value="010102">C</option> 
        <option value="010103">D</option> 
    </optgroup> 
    <optgroup label="E"> 
        <option value="010201">F</option> 
        <option value="010202">G</option> 
    </optgroup> 
</select>