The Enumerable class also has a ToList list function, which I usually use for this. http://msdn.microsoft.com/en-us/library/bb342261.aspx
Also, when using Linq to Sql, I always check the result for null. If I expect a list, make sure that the number is greater than zero before converting to a list.
public List<MyObject> GetObjects() { List<MyObject> objects = null; // no need to "new" here using (DatabaseDataContext context = new DatabaseDataContext()) { var tmp = context.GetObjectsFromDB(); if (tmp != null) { if (tmp.Count() > 0) { objects = (List<MyObject>)tmp.ToList(); } } } return objects; }
Similarly, if you expect only one result, use
myObject = (MyObject)tmp.ToSingle();
Finally, you may need to wrap this function in a try-catch block and catch a SqlException and handle the errors accordingly.
I only mention additional error handling due to application development experience that may crash if you don't have additional error handling code!
source share