nischalinn
nischalinn

Reputation: 1175

convert two LINQ queries to single query

I have made two LINQ queries one for getting Id and another for getting amount from the same model class. Since I am new to LINQ I don't know whether these two queries can be combined and get the same result.

var KID = db.Nikashas.Where(n => n.NIKASHAId == id).Select(n => n.KaryakramId).FirstOrDefault();
var KAMT = db.Nikashas.Where(n => n.NIKASHAId == id).Select(n => n.NikashaAmount).FirstOrDefault();
int kid = Convert.ToInt32(KID);
decimal kamt = Convert.ToDecimal(KAMT);

Both the above queries give the same row only selected fields are different. So is there any way I can use one single query to retrieve both the values and then how to convert KaryakramId to int and NikashaAmount to decimal?

Upvotes: 0

Views: 83

Answers (5)

monty
monty

Reputation: 8775



var res = db.Nikashas.Where(n => n.NIKASHAId == id)
    .Select(n => new { 
        kid = Convert.ToInt32(n.KaryakramId),  
        kamt = Convert.ToDecimal(n.NikashaAmount)}).FirstOrDefault();

int kid = res.kid;
decimal kamt = res.kamt;

Upvotes: 1

Sh.Imran
Sh.Imran

Reputation: 1033

The required data can be accessed with FirstOrDefault() extension and assign to anonymous type as:

var result = db.Nikashas
              .FirstOrDefault()(n => n.NIKASHAId == id)
              .Select(n => new 
               { 
                  kId = n.KaryakramId,
                  kAmt = n.NikashaAmount 
               });

From the result, required values can be accessed from anonymous type:

int kid = Convert.ToInt32(result.kId);
decimal kamt = Convert.ToDecimal(result.kAmt);

Upvotes: 2

Văn Phú Lê
Văn Phú Lê

Reputation: 31

You can use select new object with some property that you want

var result = db.Nikashas.Where(n => n.NIKASHAId == id).Select(n => new { n.KaryakramId, n.NikashaAmount}).FirstOrDefault();

Upvotes: 1

Willy David Jr
Willy David Jr

Reputation: 9161

You can use projection and assign it on anonymous type:

var KID = db.Nikashas.Where(n => n.NIKASHAId == id).Select(n => new { karya = n.KaryakramId, nika = n.NikashaAmount }).FirstOrDefault();

Then from there you can access it via properties of your anonymous type:

int kid = Convert.ToInt32(KID.karya);
decimal kamt = Convert.ToDecimal(KID.nika);

Upvotes: 4

Carl
Carl

Reputation: 2295

You could do something like this, assuming that your values are returned as strings and will be valid when converted to their types, and that the nikasha object is not too big that returning the whole thing adversely affects performance:

var nikasha = db.Nikashas.Where(n => n.NIKASHAId == id).FirstOrDefault();

//to handle a default null, check for null
if(nikasha != null)
{
    int KID = int.Parse(nikasha.KaryakramId);
    decimal KAMT = decimal.Parse(nikasha.NikashaAmount);
}

Upvotes: 1

Related Questions