views:

573

answers:

2

I tried to split a string in a linq query. I got an error says "Unrecognized expression node: ArrayIndex". Does anyone know how to achive this? My code sample is:

List<Task> Result= (from t in TaskDB.Tasks
                                       select new Task
                                       {
                                           Description = t.Description.Split('-')[0].ToString(),
                                           Id = ts.id,
                                       }).ToList();
+2  A: 

Do you really need to do the string splitting at the server side? Unless you really need to use it in a query, or if it will save a lot of bandwidth to only transfer the first part of the string, I'd fetch it all in the "LINQ to SQL" part and then post-process it with LINQ-to-Objects. Something like this:

List<Task> Result= TaskDB.Tasks.AsEnumerable() // Don't do the rest in SQL!
                               .Select(t => new Task
         {
              Description = t.Description.Split('-')[0].ToString(),
              Id = t.id,
         }).ToList();

(It'll be easier to format nicely in an IDE with slightly more columns :)

Jon Skeet
+3  A: 

The problem is that the select part of your query can't be converted into SQL to be executed on the server (hence the "unrecognised expression node" error). Try something like this, which insures that the necessary code is executed on the client side:

var result = (from t in TaskDB.Tasks.AsEnumerable()
              select new Task
              {
                  Description = t.Description.Split('-')[0].ToString(),
                  Id = ts.id,
              }).ToList();

The trick here is simply to call the AsEnumerable extension method before selecting the items.

Noldorin