按条件格式化/组的字符串列表

时间:2014-09-06 21:44:20

标签: c# list

我有关于格式化字符串列表的问题。我循环遍历两个字符串的字典:value和tagname。

myList.Add(myDict.Keys.ElementAt(n) + ":" + myDict.Values.ElementAt(n).Value);

迭代完成后,我需要格式化该字符串,如下所示:

for (int tmp = 0; tmp < myList.Count; tmp++)
{
    if (tmp < myList.Count - 1)
    {
        tempString += String.Format(myList[tmp].ToString() + " ,");
    }
}

该tempstring的输出将如下所示:TagName:Value,TagName:Value,TagName:Value。 但这里有一个棘手的部分(对我而言):几个标签名称是相同的,并且出于程序目的,这些具有相同标签名称的项目需要按照该标签名称进行分组,如下所示: TagName:value,TagName:value,value,value 你对此有什么建议吗?

更新(阅读XML):

    var evt = (from el in doc.Descendants("test")
       where el.Parent.Name == "Event_1"
       group el by el.Parent.Element("NameOfEvent").Value into g
       select new {
           Name = g.Key,
           Tests = g.Select(x => new {
               Value = x.Element("value").Value,
               TagName = x.Element("tagName").Value
           })
       }).FirstOrDefault();

     Console.WriteLine("Event name: " + evt.Name);
     foreach (var test in evt.Tests)
     {

     }

1 个答案:

答案 0 :(得分:1)

看起来你需要LINQ&#39; Group ByString.Join的组合。

Group By获取一个对象列表并生成一个对象列表列表,其中每个列表的对象都包含一些共同点。

{"Key1", "Value1"},
{"Key2", "Value2"},
{"Key1", "Value3"}

变为

{
   {"Key1", "Value1"},
   {"Key1", "Value3"}
},
{
   {"Key2", "Value2"},
}

按值分组所有值时。然后,您可以使用String.Join获取该结果并将值加入逗号分隔列表中。

您要做的是构建一个列表,其中包含在同一个键下组合在一起的所有值,然后将它们连接成一个字符串。

执行此操作有3个步骤:

  1. 按标记分组值
  2. 为每个标记的每个值构建一个字符串
  3. 构造每个其他构造字符串的最终字符串
  4. 看起来像这样:

    // Your keys and values
    List<KeyValuePair<string, string>> dict = new List<KeyValuePair<string, string>>
    {
        new KeyValuePair<string, string>("TagName1", "value1"),
        new KeyValuePair<string, string>("TagName2", "value2"),
        new KeyValuePair<string, string>("TagName1", "value3")
    };
    
    // 1. Group all of the values together based on the key
    IEnumerable<IGrouping<string, KeyValuePair<string, string>>> groupedValues = 
                dict.GroupBy(v => v.Key);
    
    // 2. Construct a string for each of the groups
    IEnumerable<string> builtValues = groupedValues.Select(group =>
    {
        // returns "TagName1:value1, value2" etc.
        return group.Key + ":" + string.Join(", ", group.Select(g => g.Value));
    });
    
    // 3. Construct the final string from each of the constructed strings
    string finalResult = string.Join(", ", builtValues);
    

    然后finalResult会包含TagName1:value1, value3, TagName:value2,这似乎是你想要的。