返回ApplicationUser对象或ApplicationUserId字符串的列表

问题描述 投票:0回答:1

我的ASP.NET核心项目中有一个Twitter风格的粉丝/后续设置。

我正在尝试构建一个LINQ查询,它将返回属于我的记录以及我所关注的用户网络。像这样的东西:

.Where(o => usersFollowingList.Contains(o.ApplicationUser.Id))

我的粉丝/后续设置是与.NET Core的IdentityUser的自引用关系:

public class ApplicationUser : IdentityUser
{
    public virtual ICollection<Network> Following { get; set; }
    public virtual ICollection<Network> Followers { get; set; }
}

public class Network
{
    public ApplicationUser ApplicationUser { get; set; }
    public string ApplicationUserId { get; set; }
    public ApplicationUser Follower { get; set; }
    public string FollowerId { get; set; }
}

此设置为我提供了我所关注的用户列表。该集合具有ApplicationUser对象及其ApplicationUserId,它是字符串类型。

我试图获取我可以在上面的WHERE子句中使用的ApplicationUser对象或ApplicationUserId字符串的集合遇到问题。

我可以得到一个我的粉丝的ApplicationUserId字符串列表,如下所示:

var g = from p in loggedinUser.Following
select p.ApplicationUser.Id.ToString();

但是这不包含我自己的ApplicationUserId。我无法轻松地将自己的ApplicationUserId添加到此集合中,因为它是IEnumerable类型。

如何获取可以在WHERE子句中使用的ApplicationUser对象或ApplicationUserId字符串的适当集合?或者有没有更好的方法来使用我的WHERE过滤器中的追随者列表?

linq asp.net-core
1个回答
1
投票

你可以使用Concat添加两个IEnumerable,所以你只需要将自己转换为单身IEnumerable。我更喜欢扩展方法:

public static IEnumerable<T> Append<T>(this IEnumerable<T> rest, params T[] last) => rest.Concat(last);

现在您可以查询为:

var g = (from p in loggedinUser.Following
         select p.ApplicationUser.Id.ToString())
        .Append(loggedinUser.Id.ToString());

但如果你已经拥有g Where物体,为什么在Following使用Network

var g = loggedinUser.Following
                    .Append(loggedinUser);

当然,你也可以做Where,但这是不必要的搜索:

.Where(o => usersFollowingList.Contains(o.ApplicationUser.Id) || o.ApplicationUser.Id == loggedinUser.Id)
© www.soinside.com 2019 - 2024. All rights reserved.