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?

+2


source to share


3 answers


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.

+3


source


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.
}

      

+4


source


You may try

var result = (from row in db.Table 
select new { CustomName = row.RowName }).Single();

      

Then you can access your property with

var foo = result.CustomName; // etc

      

+2


source







All Articles