Getting single query result with anonymous types in Linq To Sql
I have a query with only one result. The result is an anonymous type. How can I use type access so I don't have to use query.Single () every time?
This is my request:
var result = from row in db.Table
select new { CustomName = row.RowName };
This is how I am using it right now:
string name = result.Single().CustomName;
Of course my real code has many more properties and for every property I have to call. Single () every time. Is there an easier way to access the CustomName here?
source to share
Have you tried assigning the result to a Single
variable?
var singleResult = result.Single();
string name = singleResult.CustomName;
// etc...
Also, every time you call Single()
, it makes the request. You have to grab the meaning once and use it wherever you need it. As long as you use var
it should be fine, you simply cannot return this anonymous type from a method.
source to share
you can say
var result = (from row in db.Table
select new { CustomName = row.RowName }).Single();
string name = result.CustomName;
// etc.
But probably the best way is to encapsulate your result in the bonafide non-anonymous class. Then you can say
MyClass result = (from row in db.Table
select new MyClass() { CustomName = row.RowName }).Single();
string name = result.CustomName;
// etc.
Here you would, for example,
class MyClass {
public string CustomName { get; set; }
// etc.
}
source to share