user300485
user300485

Reputation: 525

Why am I not able to get this code using Linq in my asp.net mvc application?

I have this code to get all my baobjectCode from database.

    var maxCode = variables.Where(w => w.code.StartsWith(prefix) && w.code.Length == length)
        .OrderByDescending(o => o.code).Select(s => s.code).FirstOrDefault();
}

I am gettting build error in this maxcode query.

Error 8 'string' does not contain a definition for 'code' and no extension method 'code' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
Can anybody help me out why I am getting this error? Is there something I am doing wrong here?

Upvotes: 0

Views: 63

Answers (2)

archil
archil

Reputation: 39501

You are selecting BaObject.BaObjectCode list in your first statement, so variables is type of string

.Select(w => w.BaObjectCode).ToList();

you should do

 var maxCode = variables.Where(w => w.StartsWith(prefix) && w.Length == length)
    .OrderByDescending(o => o).FirstOrDefault();

in your last statement. Select is not needed at all, you can remove it

Upvotes: 2

Chris Snowden
Chris Snowden

Reputation: 5002

Add

.OrderByDescending()

before .ToList() on first line then replace the last line with:

var maxCode = variables.FirstOrDefault(w => w.StartsWith(prefix) && w.Length == length);

That should make it work.

Upvotes: 1

Related Questions