2

我有一个包含 2 列的列表,其结构如下:

50 process:3333
50 phone:xxxx
51 process:2222
51 phone:yyyy

我需要基于第一个具有这种结构的列表来构建一个新列表:

50 process:3333,phone:xxxx
51 process:2222,phone:yyyy

List 是否有任何方法可以从一列中找到相同的值并将字符串连接到第二列。

或者我必须找到一种方法来手动使用 foreach 或 while 语句?

4

2 回答 2

4

假设一个简单的结构,如......

public struct Proc
{
    public int ID { get; set; }
    public string Value { get; set; }
}

使用您的样本数据:

var procList = new List<Proc>() { 
    new Proc{ID=50,Value="process:3333"},new Proc{ID=50,Value="phone:xxxx"},
    new Proc{ID=51,Value="process:2222"},new Proc{ID=51,Value="phone:yyyy"},
};

您可以使用Enumerable.GroupByString.Join

var procIdGroupList = procList
    .GroupBy(p => p.ID)
    .Select(g => new Proc
    {
        ID = g.Key,
        Value = string.Join(",", g.Select(p => p.Value))
    }).ToList();

演示

于 2013-01-07T16:59:49.003 回答
0

找到了解决方法:

//Recupera valores dos indices para o tipo de documento
                List<Gedi.Models.OperacoesModel.imports> valuesList = new List<Gedi.Models.OperacoesModel.imports>();
                var valuesListObj = from a in context.sistema_Documentos
                                    join b in context.sistema_Indexacao on a.id equals b.idDocumento
                                    join c in context.sistema_Indexes on b.idIndice equals c.id
                                    where a.ativo == 1
                                    select new
                                    {
                                        id = a.id,
                                        values = c.idName + ":" + b.valor
                                    };

                var çist = (from x in valuesListObj.AsEnumerable()
                            select new Gedi.Models.OperacoesModel.imports
                            {
                                id = x.id,
                                values = x.values
                            }).ToList();

                var importList = çist.GroupBy(p => p.id).Select(g => new Gedi.Models.OperacoesModel.imports
                                                                        {
                                                                            id = g.Key,
                                                                            values = string.Join(",", g.Select(p => p.values))
                                                                        }).ToList();
于 2013-01-07T18:01:23.993 回答