c# - 展平 IEnumerable<string> - SelectMany 问题

标签 c# asp.net-mvc entity-framework linq lambda

我试图从表中提取 UserId's,但是当我提取它时,它以包含字符串数组的字符串数组形式出现。

我如何将它展平以得到一个字符串数组?我尝试使用 SelectMany(i => i.UserId) 但我收到错误

Cannot implicitly convert type'System.Collections.Generic.IEnumerable< char>' to'System.Collections.Generic.IEnumerable< string>'

这是为什么?为什么它认为结果是char类型的?

[DataContract]
public class AdminDashboardData
{
    [DataMember]
    public IEnumerable<string> Users { get; set; }
}

public IEnumerable<string> GetUserIds(IEnumerable<int> groupIds)
{
    using(GameDbContext entityContext = new GameDbContext())
    {
        return entityContext.InvestigatorGroupUsers
            .Include(i => i.InvestigatorGroup)
            .Where(i => i.InvestigatorGroup.IsTrashed == false)
            .Where(i => groupIds.Contains(i.InvestigatorGroupId))
            .Select(i => i.UserId).Distinct().ToFullyLoaded();
    }
}

public class InvestigatorGroupUser
{
    public int InvestigatorGroupUserId { get; set; }
    public int InvestigatorGroupId { get; set; }
    public string UserId { get; set; }
    public InvestigatorGroup InvestigatorGroup { get; set; }
}

public AdminDashboardData GetDashboardData(string userId)
{
    IGamePlayedRepository GamePlayedRepo = _GamePlayedRepo ?? new GamePlayedRepository();

    // Get the investigator groups from the userid
    IEnumerable<int> groupIds = GroupUserRepo.GetGroupIds(userId);

    AdminDashboardData data = new AdminDashboardData();

    if (!groupIds.IsNullOrEmpty())
    {
        data.Users = GroupUserRepo.GetUserIds(groupIds);
    }

    return data;
}

public static IEnumerable<T> ToFullyLoaded<T>(this IEnumerable<T> enumerable)
{
    return enumerable.ToList();
}

最佳答案

剥离本质(并替换我手边的数据库),我们有这个易于使用 LinqPad 的代码块:

void Main()
{
    GetDashboardData().Dump();
}

public IEnumerable<string> GetUserIds()
{
        return this.Peoples
            .Where(i => i.HasPhoto == false)
            .Select(i => i.FirstName).Distinct().ToFullyLoaded();
}

public IEnumerable<string> GetDashboardData()
{
    var Users = this.GetUserIds();
    return Users;
}

static class Ext
{
    public static IEnumerable<T> ToFullyLoaded<T>(this IEnumerable<T> enumerable)
    {
        return enumerable.ToList();
    }
}

这显示了一个单一维度的字符串列表。无论问题是什么,都不在这段代码中。

请记住,字符串被视为 IEnumerable<char>所以你真的得到了一个“数组(字符)数组”,但你可以把它当作一个字符串数组。

关于c# - 展平 IEnumerable<string> - SelectMany 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33025743/

相关文章:

c# - 查找文本框光标位置,行号。和列号在 asp.net 中

.net - EF在父删除时将外键设置为空

asp.net-mvc - ASP.NET MVC 报告

c# - LINQ 和 EF 与 string.StartsWith(char c)

c# - 为什么 Entity Framework 返回 null List<> 而不是空列表?

c# - return 可以抛出异常吗?

c# - 未将对象引用设置为对象的实例(将列表映射到自动映射器)

c# - 为什么 System.Data.SQLite 在 bool 列上的查询中总是返回 False?

c# - 从另一个 Controller 调用一个 Action

c# - 在 ASP.NET Core 2.0 中更新身份