展平IEnumerable<string> - SelectMany问题

3
我试图从一个表中提取UserId,但当我提取它时,它以包含字符串数组的字符串数组形式出现。如何展开它以获取一个字符串数组?我尝试使用SelectMany(i => i.UserId),但是我得到错误:

无法隐式将类型“System.Collections.Generic.IEnumerable< char>”转换为“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();
}

9
您的“UserID”是一个字符串,而不是一个字符串数组。可以枚举它以获取其字符类型为“char”的字符。这解释了异常。不需要使用SelectMany。 - Olivier Jacot-Descombes
1
方法 ToFullyLoaded() 是做什么的? - Andrey Nasonov
2
你正在对userid执行SelectMany(i => i.UserId)操作,其中userid似乎是一个字符串,因此SelectMany返回IEnumerable<char>。请解释清楚这句话的含义:“当我拉它时,它以字符串数组的形式出现”。 - Arghya C
@ArghyaC data.Users 是一个包含 string[]IEnumerable<string>。我希望它只是 IEnumerable<string> 或者 string[] - Eitan K
@EitanK,您在调试器中看到的是UsersIEnumerable<string>中声明的类型,但实际类型是string[]。这就像说“我有一只动物”,而你手里拿着的是一只狗。它并不是说IEnumerable<string>包含字符串数组。 - D Stanley
显示剩余5条评论
1个回答

0

将其简化(并替换为我手头有的数据库),我们得到了这个易于在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>,因此您实际上正在获取一个“字符数组(的数组)”,但您可以将其视为字符串数组。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接