如何返回每个结果的内部集合



我有一个查询,该查询是所有看起来像:

的用户
public class User
{
   public int Id {get;set;}
   public virtual List<Location> Locations {get;set;}
}

现在,我有了一个用户列表,但是我只想返回每个用户的位置,我该怎么做?

var users = repository.FindAll();

因此,对于每个用户,我想返回位置集合。

我不完全确定您的问题,但是实体框架与您的存储库相结合,应返回对象的主动集合。如果语法确实生成了有效的对象,那么我的假设是您具有以下数据的假设。

public class User
{
     public int Id { get; set; }
     public string Name { get; set; }
     public List<Location> Locations { get; set; }
}

您可以简单地做:

var locations = users.GetAllUsers()
                     .Select(user => user.Locations)
                     .SelectMany(location => location)
                     .Distinct();

因此,选择位置对象,然后将其弄平以获取所需的数据,然后不同以删除重复项。因此,您将收到与用户相关的所有位置。您可以混合并匹配LINQ,以完成许多不同的方式。我可能有语法或反转SelectSelectMany,因为我一直被中断,但这至少应该对您有所帮助。

首先,您应该将所有位置提取,然后将其合并到单个列表

var mergedList = MergeLists(users.Select(x => x.Locations).ToList());

订婚者看起来像这样

    List<Location> MergeLists(List<List<Location>> listsOfLists)
    {
        List<Location> mergedList = new List<Location>();
        foreach (List<Location> listLocation in listsOfLists)
        {
            mergedList.AddRange(listLocation);
        }
        return mergedList;
    }

编辑。更优雅的解决方案

users.Select(x => x.Locations).SelectMany(x => x).ToList();

最新更新