如何使用LINQ合并列表中行的数据?

时间:2019-04-15 03:50:56

标签: c# linq

我有一个包含两个属性的列表,分别是Sequence和Term。

termData <int,string> 

每个序列可以有多个术语。

有没有一种方法,我可以将每个序列号的术语组合在一起,从而创建另一个类似于以下内容的列表:

1438690“天气;要素;晴朗的天气

enter image description here

4 个答案:

答案 0 :(得分:3)

var _result = termData.GroupBy(x => x.Sequence)
                .Select(x => new
                {
                    seq = x.Key,
                    term = x.Select(y => y.Term).ToList()
                });

答案 1 :(得分:2)

var list = new List<termData>();
list.Add(new termData() { Sequence = 1438690, Terms = "weather" });
list.Add(new termData() { Sequence = 1438690, Terms = "the elements" });
list.Add(new termData() { Sequence = 9672410, Terms = "dogs" });
list.Add(new termData() { Sequence = 9672410, Terms = "cats" });

var result = list
    .GroupBy(t => t.Sequence, t => t.Terms)
    .Select(g => g.Key + ";" + String.Join(";", g));
foreach (var item in result)
{
    Console.WriteLine(item);
}

输出:

1438690;weather;the elements
9672410;dogs;cats

答案 2 :(得分:1)

只要您拥有一系列带有单个键引用多个项目的项目,就可以使用Lookup对象:

var lookup = list.ToLookup( item => item.Sequence, item => item.Terms);

此代码告诉c#创建一个查找,就像一个字典,其中item.Sequence是键,item.Terms是值。该值本身是一个可以枚举的列表:

foreach (var item in lookup)
{
    Console.WriteLine("Sequence {0} has these terms: {1}", item.Key, string.Join(",", item));
}

输出:

Sequence 1438690 has these terms: weather,the elements
Sequence 9672410 has these terms: dogs,cats

DotNetFiddle上查看我的工作示例

答案 3 :(得分:0)

>>> s1 = set([1,2,3])
>>> s2 = 2,3,4
>>> s3 = 3,4,5
>>> s1.intersection(s2,s3)
set([3])

下面是获取seq项的功能。

 public class SeqTerm
        {
            public string Seq { get; set; }
            public List<string> lstTerms { get; set; }
        }