0

I am using linq to sql for my project. But getting error after I am converting the result of ExecuteQuery() using the .ToList() extension:

var logentries = DB.ExecuteQuery<keyValueList>(string.Format(query));
keyValueList kv1 = logentries.ToList();// -->Error in this line as: 

Error:

Cannot implicitly convert type 'System.Collections.Generic.List' to 'DataLib.keyValueList'

Chris
  • 8,527
  • 10
  • 34
  • 51
sameer pradhan
  • 324
  • 1
  • 4
  • 14

1 Answers1

0

ToList returns a List<T> where T is keyValueList. But i think you want a single object, then either use First/FirstOrdefault or Singler/ SingleOrDefault:

keyValueList kv1 = logentries.FirstOrDefault();

The diference is, the ...OrDefault methods return null if the input sequnce is empty whereas the First/Single throw an exeption. Furthermore Single throws an exception if there is more than one item(useful if that is impossible and should throw, for example because you are filtering by a unique property).

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • And you may want to check if List.Count() > 0 before you use First() or FirstOrDefault(). I've been burned too many times w/ FirstOrDefault(). – WEFX Sep 03 '13 at 12:47
  • 2
    @WEFX: Never use `Count()` if you want to know if there is one, use `Any`. Otherwise you will execute the whole query and count each item just to know that there's at least one. If you use `FirstOrDefault` you don't need to use `Any`. Just check `if(kv1 != null) ....`. – Tim Schmelter Sep 03 '13 at 12:49
  • Actually i want to return a list from the select query. As i am using Datacontext Just want to know also what ExecuteQuery() is going to return. I thought i'll use logentries in foreach to get the desired list and will return it. – sameer pradhan Sep 04 '13 at 04:14
  • @sameerpradhan: Then you want a `List kv1 = logentries.ToList();`. – Tim Schmelter Sep 04 '13 at 06:51