如何在LINQ C#中将来自不同类型的2个集合合并为一个自定义类型?

时间:2018-03-16 19:16:32

标签: c# .net linq collections

我想基于来自不同类型的2个列表创建对象列表。 我现在有一个代码片段,但是我想知道它是否可以转换为LINQ以使其更小更高效。

List<Region> regions = new List<Region>
            {
                new Region
                {
                    Name = "America"
                },
                new Region
                {
                    Name = "Europe"
                },
                new Region
                {
                    Name = "Asia"
                }
            };

            List<Concept> concepts = new List<Concept>
            {
                new Concept
                {
                    Name = "Population"
                },
                new Concept
                {
                    Name = "Location"
                },
                new Concept
                {
                    Name = "Temperature"
                },
                new Concept
                {
                    Name = "President"
                }
            };

            List<object> result = new List<object>();

            foreach (var region in regions)
            {
                foreach (var concept in concepts)
                {
                    result.Add(new { region = region.Name, concept = concept.Name });
                }
            }

4 个答案:

答案 0 :(得分:1)

您可以在LINQ中执行等效的交叉连接,如下所示:

var regionConcepts = regions.SelectMany(x => concepts.Select(y => new { Region = x.Name, Concept = y.Name }));

答案 1 :(得分:0)

使用linq查询:

        var results = from region in regions
                      from concept in concepts
                      select new
                      {
                          region = region.Name,
                          concept = concept.Name
                      };

答案 2 :(得分:0)

这样的事情:

var result = regions.SelectMany(r => concepts, (r, c) => new Tuple<Region, Concept>(r, c));

答案 3 :(得分:0)

这相当于您的代码目前使用LINQ执行的操作。

List<object> resultSet = regions.SelectMany(region => 
                        concepts.Select(concept => new { 
                                Region = region.Name, Concept = concept.Name })
                        )
                        .Cast<object>()
                        .ToList();

另一种变体:

List<object> resultSet = (from region in regions
                          from concept in concepts
                          select new
                          {
                              region = region.Name,
                              concept = concept.Name
                          }).Cast<object>()
                            .ToList();