将IEnumerable分组为一个字符串

时间:2015-07-27 12:35:23

标签: c# asp.net-mvc-4 umbraco

我想知道是否有人可以在几分钟内给我一些建议?

我创建了一个IEnumerable列表:

public class EmailBlock
{
    public int alertCategory { get; set; }
    public string alertName { get; set; }
    public string alertURL { get; set; }
    public string alertSnippet { get; set; } //Need to work out the snippet
}

List<EmailBlock> myEmailData = new List<EmailBlock>();

然后我循环浏览一些数据(Umbraco内容 - 而不是真的相关!)并将项目添加到列表中。

 myEmailData.Add(new EmailBlock { alertCategory = category.Id, alertName = alert.GetPropertyValue("pageTitle"), alertURL = alert.NiceUrl });

我最终要做的是按alertCategory对列表进行分组,然后加载每个&#39;组&#39; (稍后会发生另一个循环以检查成员订阅了哪些警报类别)到变量中,然后我可以将其用作电子邮件的内容。

2 个答案:

答案 0 :(得分:4)

您可以使用Linq的GroupBy()执行此操作:

using System.Linq
...

//Create a type to hold your grouped emails
public class GroupedEmail
{
    public int AlertCategory { get; set; }

    public IEnumerable<EmailBlock> EmailsInGroup {get; set; }
}

var grouped = myEmailData
    .GroupBy(e => e.alertCategory)
    .Select(g => new GroupedEmail
    {
        AlertCategory = g.Key,
        EmailsInGroup = g
    });

如果需要,您可以选择匿名类型,并将序列投射到您需要的任何结构中。

答案 1 :(得分:3)

Linq有一个很好的小组声明:

var emailGroup = emailList.GroupBy(e => e.alertCategory);

然后你可以遍历每个分组并做你想做的事情:

foreach(var grouping in emailGroup)
{
  //do whatever you want here. 
  //note grouping will access the list of grouped items, grouping.Key will show the grouped by field
}

编辑:

要在对群组进行分组后检索群组,只需将Where用于多个群组,或仅First使用一个群组:

var group = emailGroup.First(g => g.Key == "name you are looking for");

var groups = emailGroup.Where(g => listOfWantedKeys.Contains(g.Key));

这比每次需要查找内容时循环更有效。