dstr
dstr

Reputation: 8928

Getting single result from a query with anonymous types in Linq To Sql

I have a query with single result. The result is an anonymouse type. How can I use access the type so I don't have to use query.Single() every time?

This is my query:

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

This is how I use it right now:

string name = result.Single().CustomName;

Of course my real code has a lot more properties and for every property I have to call .Single() every time. Is there an easier way to access CustomName here?

Upvotes: 2

Views: 1853

Answers (3)

Vanilj
Vanilj

Reputation: 104

You could 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

Upvotes: 2

jason
jason

Reputation: 241583

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 into a 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 have, for example,

class MyClass {
    public string CustomName { get; set; }
    // etc.
}

Upvotes: 4

dahlbyk
dahlbyk

Reputation: 77500

Have you tried assigning the Single result to a variable?

var singleResult = result.Single();
string name = singleResult.CustomName;
// etc...

Furthermore, each time you call Single() it will execute the query. You should grab the value once and use it wherever you need. As long as you use var you should be fine, you just can't return that anonymous type from a method.

Upvotes: 3

Related Questions