chetan
chetan

Reputation: 51

C# cannot convert int to string

var query = from s in student
            select new ListItem
            {
                ID = s.studentId, 
                Name = s.studentName
            };

When I tried to execute the code I got the error

//Cannot implicitly convert type 'int' (studentId) to 'string' (ID).

Is there anyway I can achieve this?

Upvotes: 0

Views: 5293

Answers (5)

Kishore Kumar
Kishore Kumar

Reputation: 12874

create a new variable with var type and assign the value of studentid to that vaiable and use the new one in your linq

Upvotes: 0

Alexander Yezutov
Alexander Yezutov

Reputation: 3214

Did you try 'ToString()'?

var studentId = s.studentId.ToString();
var query = from s in student select new ListItem { ID = studentId, Name = s.studentName };

Upvotes: 1

user1082916
user1082916

Reputation:

Use Convert.ToString() method.....Convert.ToString(obj) doesn't need to presume the object is not null (as it is a static method on the Convert class), but instead will return String.Empty if it is null.....

 var query = from s in student
                        select new ListItem
                        {
                            ID = Convert.ToString(s.studentId),
                            Name = s.studentName
                        };

Upvotes: 0

V4Vendetta
V4Vendetta

Reputation: 38210

Since you are using LINQ to Entities ToString won't work for you instead you will have to try out

SqlFunctions.StringConvert((double)s.studentId) //since there is no overload for int

Check this out Sql Functions

Upvotes: 1

Stefan
Stefan

Reputation: 5672

The ListItem does not contain an ID property. Try using one of its constructors;

var query = from s in student select new ListItem(s.studentName, s.studentId.ToString());

Upvotes: 0

Related Questions