C# 将IEnumerable分组为字符串

C# 将IEnumerable分组为字符串,c#,asp.net-mvc-4,umbraco,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

不知是否有人能抽出几分钟时间给我一些建议

我已经创建了一个
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>();
最后,我想做的是按
alertCategory
对列表进行分组,然后将每个“组”(稍后会出现另一个循环,以检查哪些成员订阅了哪个警报类别)加载到一个变量中,然后我可以将其用作电子邮件内容。

您可以使用Linq来执行此操作:

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
    });
使用System.Linq
...
//创建一个类型来保存分组的电子邮件
公共类群发邮件
{
公共int AlertCategory{get;set;}
公共IEnumerable EmailsInGroup{get;set;}
}
var group=myEmailData
.GroupBy(e=>e.alertCategory)
.选择(g=>newgroupedemail
{
AlertCategory=g.键,
EmailsInGroup=g
});

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

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");


这比每次需要查找内容时循环查找要高效得多。

#oliver#pquest为大家干杯,这样可以将所有内容组合在一起(谢谢)。那么,是否可以将每个组加载到一个字符串(或一系列字符串)中,以便我以后掌握?@SxChoc您的意思是将键加载到一个字符串列表中?我可能解释得不太清楚!最后,我将得到六个分组的“things”,然后我希望将每个分组加载到一个唯一的变量中,以便在代码中稍后我可以检查一系列用户,以检查他们注册的alertCategory,并将相关字符串插入电子邮件中,然后发送。@SxChoc如果说alertCaregory是foo,你可能想要
var foo=emailGroup.First(g=>g.Key==“foo”)
?这就是我想要的,但是alertCategory不是固定数量的类别,所以我需要一些动态的东西(如果我在这里太傻了,我道歉…我醒得太久了!)
var group = emailGroup.First(g => g.Key == "name you are looking for");
var groups = emailGroup.Where(g => listOfWantedKeys.Contains(g.Key));