本文介绍了LINQ:如何通过这样的元素进行分组可以被添加到很多组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3种类型:参数,设施和位置。 参数有一个设施和设施与多对多 - Location 。所以,如果我们建立一个连接,我们可以得到这样一个表:

 参数ID FacilityId LocationId 
1 1 1
1 1 2
2 2 1
2 2 3

现在我想按位置对参数进行分组,以便我得到一个Dictionary>,如下所示:

  LocationId参数
1 1,2
2 1
3 2

我不能做直接GroupBy,因为我不知道如何写一个keySelector。我也尝试过这样的SelectMany:

  parametersList.SelectMany(t => t.Facility.Locations).GroupBy(t = > t)
.ToDictionary(t => t.Key,t => t.Select(val => val))

但它无法形成我的字典..



更新:
这是我的Facility(简化)的样子:

  public class Facility 
{
public int Id {get;组; }
public ICollection< Location>地点{get;组; }
}

这里是位置:

  public class Location 
{
public int Id {get;组; }
public ICollection< Facility>设施{get;组; }
}

我会很乐意为您提供任何帮助!

解决方案

此查询返回您想要的结果:

  parametersListList 
.SelectMany(_ => _.Facility.Locations)
.GroupBy(_ => _)
.ToDictionary(
_ => _.Key,
_ => _.SelectMany(l => l.Facilities).SelectMany(f => f.Parameters).Distinct()。ToArray());

更新
<您可以使用 parametersList 或存储参数:

  parametersListList 
.SelectMany(_ => _.Facility.Locations)
.GroupBy(_ => _)
.ToDictionary(
_ => _.Key,
_ => _.SelectMany(l => l.Facilities).Select(f => parametersList.Single(p => p.Facility == f))Distinct()。ToArray ));


I have 3 types: Parameter, Facility and Location. Parameter has one Facility and Facility is related many-to-many with Location. So, if we make a join, we can get such a table:

ParamId FacilityId LocationId
1            1          1
1            1          2
2            2          1
2            2          3

Now i want to group my parameters by locations so that i get a Dictionary>, like this:

LocationId   Parameters
     1          1,2
     2           1
     3           2

I can't do a straight GroupBy because i don't know how to write a keySelector. I Also tried SelectMany like this:

parametersList.SelectMany(t=>t.Facility.Locations).GroupBy(t =>t)
.ToDictionary(t=>t.Key, t=>t.Select(val=>val))

but it cannot form me my Dictionary..

Update:Here is how my Facility (simplified) looks like:

public class Facility
{
    public int Id { get; set; }
    public ICollection<Location> Locations { get; set; }
}

and here is Location:

public class Location
{
    public int Id { get; set; }
    public ICollection<Facility> Facilities { get; set; }
}

I'll be gratefull for any help!

解决方案

This query return that you want:

parametersList
        .SelectMany(_ => _.Facility.Locations)
        .GroupBy(_ => _)
        .ToDictionary(
            _ => _.Key, 
            _ => _.SelectMany(l => l.Facilities).SelectMany(f => f.Parameters).Distinct().ToArray());

UPDATE

You can use parametersList or store of parameters for it:

parametersList
        .SelectMany(_ => _.Facility.Locations)
        .GroupBy(_ => _)
        .ToDictionary(
            _ => _.Key, 
            _ => _.SelectMany(l => l.Facilities).Select(f => parametersList.Single(p => p.Facility == f)).Distinct().ToArray());

这篇关于LINQ:如何通过这样的元素进行分组可以被添加到很多组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 16:32