展平IEnumerable <string> - SelectMany问题

时间:2015-10-08 20:52:47

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

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

如何将其展平以获得字符串数组?我尝试过使用SelectMany(i => i.UserId),但我收到了错误

  

无法隐式转换类型&#39; System.Collections.Generic.IEnumerable&lt;炭&GT;&#39;到&#39;&System.Collections.Generic.IEnumerable LT;串GT;&#39;

这是为什么?为什么它认为结果是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();
}

1 个答案:

答案 0 :(得分: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>,所以你真的得到了一个“数组数组(字符数组)”,但你可以把它当作一个字符串数组。