【问题标题】:Return List of either ApplicationUser objects or ApplicationUserId strings返回 ApplicationUser 对象或 ApplicationUserId 字符串的列表
【发布时间】:2018-03-06 07:59:17
【问题描述】:

我的 ASP.NET Core 项目中有一个 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】:

    您可以使用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());
    

    但是,如果您已经拥有 Following Network 对象,为什么还要在 Where 中使用 g

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

    当然,您也可以使用Where,但这是不必要的搜索:

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

    【讨论】:

    • 谢谢@NetMage。我将标记为“已回答”。只是想跟进您的线路:“但是,如果您已经拥有以下网络对象,为什么要在 Where 中使用 g 呢?”。如何使用关注网络对象? WHERE 需要 ApplicationUser 或 Id。我似乎无法让查询使用来自 Network 对象的信息。有任何想法吗? :)
    • “关注”属于“网络”类型。但我需要在查询中输入 ApplicationUser。
    • 我的问题是你为什么需要查询;当Following 已经包含您的Where 似乎正在返回的网络对象时,为什么还要使用Where
    猜你喜欢
    • 2014-08-25
    • 1970-01-01
    • 2016-08-15
    • 2015-09-17
    • 1970-01-01
    • 1970-01-01
    • 2011-04-01
    • 2017-10-17
    • 1970-01-01
    相关资源
    最近更新 更多