简体   繁体   中英

LINQ to Entities split string on result

I have a LINQ statement as follows:

var playedBanDataList =
    from bannedPlayers in query
    select new PlayerBanData
    {
        Admin = bannedPlayers.Admin,
        BannedUntil = bannedPlayers.BannedUntil,
        IsPermanentBan = bannedPlayers.IsPermanentBan,
        PlayerName = bannedPlayers.PlayerName,
        Reason = bannedPlayers.Reason,
        IpAddresses = bannedPlayers.IpAddresses.Split(new [] {","}, StringSplitOptions.RemoveEmptyEntries).ToList()
    };

    return playedBanDataList.ToList();

This fails because split function fails on IpAddresses as LINQ to Entities cannot translate this query to SQL.

This makes sense, but then what's an equivalent way of accomplishing this elegantly? The only way I've thought of is to manually run a loop on the retrieved string then splitting it, but I'd like to get it in one go.

You can use AsEnumerable to make the select occur in memory instead of EF.

var playedBanDataList = query.AsEnumerable()
    .Select(bannedPlayers => new PlayerBanData
    {
        Admin = bannedPlayers.Admin,
        BannedUntil = bannedPlayers.BannedUntil,
        IsPermanentBan = bannedPlayers.IsPermanentBan,
        PlayerName = bannedPlayers.PlayerName,
        Reason = bannedPlayers.Reason,
        IpAddresses = bannedPlayers.IpAddresses.Split(
            new [] {","}, 
            StringSplitOptions.RemoveEmptyEntries).ToList()
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM