我有一个包含2列的List,结构如下:
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语句手动找到一种方法吗?
答案 0 :(得分: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.GroupBy
和String.Join
:
var procIdGroupList = procList
.GroupBy(p => p.ID)
.Select(g => new Proc
{
ID = g.Key,
Value = string.Join(",", g.Select(p => p.Value))
}).ToList();
<强> DEMO 强>
答案 1 :(得分: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();