简体   繁体   English

时间:2019-05-10 标签:c#group list items里面有部分相同的文本

[英]c# group list items that have part of the same text inside

I have this list listemailsMsgs that have items like this:我有这个列表 listemailsMsgs 有这样的项目:

email1@hotmail.com;mensagem1;assunto1
email2@hotmail.com;mensagem1;assunto1
email3@hotmail.com;mensagem2;assunto2

The first two items have different emails, but the messages are the same.前两项具有不同的电子邮件,但消息相同。 The third item has a different email and a different message.第三项具有不同的电子邮件和不同的消息。

I am having a hard time finding a way to group the first two items into just one, like this:我很难找到将前两个项目组合成一个的方法,如下所示:

email1@hotmail.com;email2@hotmail.com;mensagem1;assunto1

Does anyone have any idea of how to do that?有谁知道如何做到这一点?

First and foremost, try to convert the given values into ac# model, so that it will be easy for you to solve this kind of problem.首先,尝试将给定的值转换为 ac# 模型,这样您就可以轻松解决此类问题。

In the mentioned question, the item value contains the three sections, so create an Item class to represent it.在提到的问题中,item 值包含三个部分,因此创建一个 Item 类来表示它。

    public class Item
    {
        public string EmailAddress { get; }
        public string FirstMessageField { get; }
        public string SecondMessageField { get; }

        public Item(string message)
        {
            var result = message.Split(';');
            EmailAddress = result[0];
            FirstMessageField = result[1];
            SecondMessageField = result[2];
        }
    }

Then, convert all your given string values into a List of Item.然后,将所有给定的字符串值转换为项目列表。

        var input = new List<Item>
        {
            new Item("email1@hotmail.com;mensagem1;assunto1"),
            new Item("email2@hotmail.com;mensagem1;assunto1"),
            new Item("email3@hotmail.com;mensagem2;assunto2")
        };

Finally, use LINQ operations to group your values based on the message fields:最后,使用 LINQ 操作根据消息字段对值进行分组:

        var output = input
            .GroupBy(x => new { x.FirstMessageField, x.SecondMessageField })
            .Select(x =>
            {
                var emailAddresses = string.Join(';', x.Select(y => y.EmailAddress).ToArray());
                return $"{emailAddresses};{x.Key.FirstMessageField};{x.Key.SecondMessageField}";
            })
            .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM