Error when splitting and replacing chars C# email with LINQ Array Index not supported in LINQ

大兔子大兔子 提交于 2020-01-16 20:05:03

问题


This throws an error 'ArrayIndex' is not supported in LINQ to Entities. so what would be an alternative for this as the split and replace fails?

from S in db.Students
where S.ID = ID
select new { S.EMAIL.Split('@')[0].Replace(".", " ,"), S.NAME };

This is for a list of Students and this is how I currently can add them.

mylist.DataValueField = "email";
mylist.DataTextField = "name";

This fails:

S.EMAIL.Split('@')[0].Replace(".", " ,")

Please help.

Thanks


回答1:


If you want it to run on the SQL server you can use IndexOf and Substring:

from S in db.Students
where S.ID = ID
select new 
{ 
    EMAIL = (S.EMAIL.Contains("@") ? 
                S.EMAIL.Substring(0, S.EMAIL.IndexOf("@")) : 
                S.EMAIL
            ).Replace(".", " ,")
  , S.NAME 
};



回答2:


You could do the following

var query =  (from S in db.Students
             where S.ID = ID
             select new { 
                 S.EMAIL, 
                 S.NAME })
             .AsEnumerable()
             .Select(x => new {
                  EMAIL = x.EMAIL.Split('@')[0].Replace(".", " ,"), 
                  NAME = x.NAME});

So that the splitting and replacing is done in linq to objects instead of the DB.



来源:https://stackoverflow.com/questions/29540398/error-when-splitting-and-replacing-chars-c-sharp-email-with-linq-array-index-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!