-1

Is it possible to convert Int32 to string?

I am having difficulties with this line of the code, where I am trying to convert Int32 to string.

var listOrder = daa.OrderByDescending(i => i.Times).ToList().Convert.ToString().OrderByDescending(jtSorting);

i.Times is Int32 and I have to pass jSorting parameter which is string.

I get this error when I compile:

"Does not contain a defination for 'Convert' and no extension method 'Convert' accepting a first argument of type"

Full controller code for your inspection:

public JsonResult TopPlayedInVenueList1(string name = "", string ArtistName = "", int jtStartIndex = 0, int jtPageSize = 0, string jtSorting = null)
    {
        try
        {
            if (Request.IsAuthenticated == true)
            {
                string Path = @"C:\\5Newwithdate-records.xls";
                OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= '" + 
                                                            Path + "';Extended Properties=" + (char)34 + 
                                                            "Excel 8.0;IMEX=1;" + (char)34 + "");
                OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", con);

                System.Data.DataTable data = new System.Data.DataTable();
                da.Fill(data);
                con.Close();

                List<TopPlayed> daa = new List<TopPlayed>();
                foreach (DataRow p in data.Rows)
                {
                    TopPlayed top = new TopPlayed()
                    {
                        TrackID = Convert.ToInt32(p.Field<double>("TrackID")),
                        TrackName = p.Field<string>("TrackName"),
                        ArtistName = p.Field<string>("ArtistName"),
                        Times = Convert.ToInt32(p.Field<double>("Times"))
                    };

                    daa.Add(top);
                }

                ///// var newlist = daa.OrderByDescending(i => i.Times).ToList().GetRange(jtStartIndex, jtPageSize);

                var newlist = daa.AsQueryable().OrderByDescending(jtSorting).OrderByDescending(i => i.Times).ToList();

                return Json(new { Result = "OK", Records = newlist, TotalRecordCount = daa.Count });

View Code of jTable Datatable:

 $(document).ready(function () {
    $('#TopPlayedInVenueContainer1').jtable({

        title: 'NSM Biling Report List',
        paging: true,
        pageSize: 100,
        sorting: true,
      //  defaultSorting: 'Times ASC',

        actions: {
            listAction: '@Url.Action("TopPlayedInVenueList1")'

        },
        fields: {
            TrackID: {
                title: 'Track ID',
                key: true,
                create: false,
                edit: false,
                resize: false,
                tooltip: 'Track Name'
            },
            TrackName: {
                title: 'Track Name',
                key: true,
                create: false,
                edit: false,
                resize: false,
                tooltip: 'Track Name'
            },
            ArtistName: {
                title: 'Artist Name',
                key: true,
                create: false,
                edit: false,
                resize: false,
                tooltip: 'Track Name'
            },
            Times: {
                title: 'Times',
                tooltip: 'Artist Name'
            }
        }
    });

    $('#LoadRecordsButton').click(function (e) {
        e.preventDefault();
        $('#TopPlayedInVenueContainer1').jtable('load', {
            name: $('#name').val(),
            ArtistName: $('#ArtistName').val()
        });
    });

    //Load all records when page is first shown
    $('#LoadRecordsButton').click();
});

OrderByExtensions

namespace NSM.BackOffice.Controllers
{
public static class OrderByExtensions
{
    public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string ordering)
    {
        var type = typeof(T);
        var property = type.GetProperty(ordering);
        var parameter = Expression.Parameter(type, "p");
        var propertyAccess = Expression.MakeMemberAccess(parameter, property);
        var orderByExp = Expression.Lambda(propertyAccess, parameter);
        MethodCallExpression resultExp = Expression.Call(typeof(Queryable), "OrderBy", new Type[] { type, property.PropertyType }, source.Expression, Expression.Quote(orderByExp));
        return source.Provider.CreateQuery<T>(resultExp);
    }

    public static IQueryable<T> OrderByDescending<T>(this IQueryable<T> source, string ordering)
    {
        var type = typeof(T);
        var property = type.GetProperty(ordering);
        var parameter = Expression.Parameter(type, "p");
        var propertyAccess = Expression.MakeMemberAccess(parameter, property);
        var orderByExp = Expression.Lambda(propertyAccess, parameter);
        MethodCallExpression resultExp = Expression.Call(typeof(Queryable), "OrderByDescending", new Type[] { type, property.PropertyType }, source.Expression, Expression.Quote(orderByExp));
        return source.Provider.CreateQuery<T>(resultExp);
    }
}

}

I am fresh with c# so if you could please let me know a workout to get this to work. thanks in advance.

pv619
  • 385
  • 5
  • 24

6 Answers6

3

You can call ToString during projection in Enumerable.Select

var listOrder = daa.OrderByDescending(i => i.Times).Select(c=>c.Times.ToString()).ToList();
Adil
  • 139,325
  • 23
  • 196
  • 197
  • thanks.. I have to pass `jtSorting` parameter in it which is a string. I have updated a full code on mine. – pv619 Apr 02 '14 at 09:48
  • You need c.Times.ToString(), please check my updated answer and use that query – Adil Apr 02 '14 at 09:53
2

This part:

OrderByDescending(i => i.Times).ToList().Convert.ToString()

looks very strange. Convert here is not a property and not a method call. You might probably want this instead:

OrderByDescending(i => i.Times).ToList().Select(x => x.ToString())

Update. Following up discussion in comments - here is how to use the extension method implemented here. Declare a static class somewhere in the project like this:

public static class OrderByExtensions
{
    public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string ordering) {
        var type = typeof(T);
        var property = type.GetProperty(ordering);
        var parameter = Expression.Parameter(type, "p");
        var propertyAccess = Expression.MakeMemberAccess(parameter, property);
        var orderByExp = Expression.Lambda(propertyAccess, parameter);
        MethodCallExpression resultExp = Expression.Call(typeof(Queryable), "OrderBy", new Type[] { type, property.PropertyType }, source.Expression, Expression.Quote(orderByExp));
        return source.Provider.CreateQuery<T>(resultExp);
    }

    public static IQueryable<T> OrderByDescending<T>(this IQueryable<T> source, string ordering) {
        var type = typeof(T);
        var property = type.GetProperty(ordering);
        var parameter = Expression.Parameter(type, "p");
        var propertyAccess = Expression.MakeMemberAccess(parameter, property);
        var orderByExp = Expression.Lambda(propertyAccess, parameter);
        MethodCallExpression resultExp = Expression.Call(typeof(Queryable), "OrderByDescending", new Type[] { type, property.PropertyType }, source.Expression, Expression.Quote(orderByExp));
        return source.Provider.CreateQuery<T>(resultExp);
    }
}

Make sure this class is visible inside the TopPlayedInVenueList1, if not - use using to make so. After that you should be able to do this with any IQueryable<>:

.OrderByDescending(jtSorting);
Community
  • 1
  • 1
Andrei
  • 53,252
  • 9
  • 82
  • 104
  • that's great and thanks.. It won't let me to pass `jtSorting` string parameter in it – pv619 Apr 02 '14 at 09:55
  • @pv619, now I see your problem. All right, passing property name into `OrderBy` is a well known question, which has a lot of answers. Check out [this one](http://stackoverflow.com/questions/307512/how-do-i-apply-orderby-on-an-iqueryable-using-a-string-column-name-within-a-gene), for example – Andrei Apr 02 '14 at 09:59
  • sorry for not being clear.. thanks for the link and I checked the post it's somewhat different and I am not sure what to do. Can you help? I have to add `jtSorting` parameters so that it enables on server-side. thanks again :) – pv619 Apr 02 '14 at 10:28
  • @pv619, add where? Enables what? As far as I can see you are trying to order a collection of objects by their property, and you have a string with property name. Is that right? – Andrei Apr 02 '14 at 10:42
  • @pv619, then the link above is exactly what you need. Check out first answer. It defines an extension methods `OrderBy` and `OrderByDescending` accepting string for property name. So what you need to do is: 1) Create the same extension method somewhere in your project, 2) call it exactly as you arecalling it now – Andrei Apr 02 '14 at 10:48
  • thanks for getting back and let me do that and I'll get back to you asap. :) cheers – pv619 Apr 02 '14 at 10:51
  • I tried it man but it started to give me all sorts of errors.. i.e. `var` is not defined, an `object` reference is required for `ordering` , same errors for `parameters`.. man i'm not too sure how I can get this sorting thing to work. – pv619 Apr 02 '14 at 11:27
  • here's the [link](http://s9.postimg.org/x6fzuaa7j/Capture.png) in using the extension method. I see what you mean, so even if I can get this code to work then it would be great. – pv619 Apr 02 '14 at 11:50
  • @pv619, you really need to read some tutorial on exntesion methods. Extension method should be a part of some dedicated static class. Do you have one? – Andrei Apr 02 '14 at 11:52
  • thanks - Yes I do have them but they're being used for other functions. So I created a brand new Class and in it I added the extension that gave me soo many errors. – pv619 Apr 02 '14 at 11:57
  • @pv619, please see the update - hope its clear now. If still not - please look up some extension methods usage example – Andrei Apr 02 '14 at 12:06
  • man thanks for your answer and help throughout, I created a brand new `Controller` class of `OrderByExtensions` without any issue. I feel awkward for asking and sorry for the trouble.. it still won't let me use `var list = daa.ToList().OrderByDescending(jtSorting);` says "cannot be inferred from the usage". I think we're almost there! and thanks a million once again! - u been an awesome help :) – pv619 Apr 02 '14 at 12:59
  • I used this `var newlist = daa.AsQueryable().OrderByDescending(jtSorting).OrderByDescending(i => i.Times).ToList();` without any errors and compiled fine but it didn't display any data and the datatable gave out this message out "Value cannot be null. Parameter name: name" is that because jtSorting is a null string by default? any idea?? I think we are missing a small bit.. almost there! ehehe :) – pv619 Apr 02 '14 at 14:09
  • @pv619, at what line of code is the exception falling? – Andrei Apr 02 '14 at 17:44
  • Hi.. and thanks for getting back :) this is the line that keeps on giving error: `var list = daa.ToList().OrderByDescending(jtSorting);` when I use `.OrderByDescending(jtSorting);` and gives out **Cannot be inferred from the usage"** – pv619 Apr 03 '14 at 06:38
  • as I am using `IQueryable` so I tried `.AsQueryable()` like this `var newlist = daa.AsQueryable().OrderByDescending(jtSorting).OrderByDescending(i => i.Times).ToList();` then it complies fine but doesn't display any data and the jQuery jTable gives out this message `Value cannot be null. Parameter name: name`. The only `null` parameter that I am using is `jtSorting`. I have updated my full code for your inspection. And above all thanks a million! :) – pv619 Apr 03 '14 at 06:42
  • Do we have to declare `jtSorting` in the `OrderByExtensions` class? so that it takes all the `.OrderByDescending(jtSorting);` arguments? thanks :) – pv619 Apr 03 '14 at 06:55
2

You jsSorting parameter is for sorting datatables, not IEnumerables: Try this:

data.DefaultView.Sort = jsSorting;   
Peter
  • 26,307
  • 7
  • 58
  • 80
  • thanks for your suggestion and it works but it won't let me pass `jtSorting` parameter in it which is a string. – pv619 Apr 02 '14 at 09:53
  • thanks for getting back :) - I tried what you suggested, it seems to be loading the sorting but it ain't really doing it. I have updated my code with your code :) – pv619 Apr 02 '14 at 10:51
0

You are trying to convert your list object to a string:

var listOrder = daa.OrderByDescending(i => i.Times).ToList().Convert.ToString();

What you may want (and I don't know your requirements is):

var listOrder = daa.OrderByDescending(i => i.Times).Select(i => i.Times.ToString()).ToList();

Which would give you a list of strings.


As per your comment, if the technique noted is beyond you, you could do this (and this might be fine if there are a limited number of columns that you want to sort by):

List<TopPlayed> sorted;

switch (jtSorting)
{
   case "Times":
      sorted = daa.OrderByDescending(i => i.Times).ToList();
      break;
   case "Other":
      sorted = daa.OrderByDescending(i => i.Other).ToList();
      break;
    default:
      //Oops.  Do something appropriate here.
}

// etc.
Paddy
  • 31,468
  • 14
  • 75
  • 108
  • thanks :) it works great but I got to pass `jtSorting` parameter in it for it to enable sorting. – pv619 Apr 02 '14 at 09:52
  • OK, wasn't so clear. You might try: http://stackoverflow.com/questions/41244/dynamic-linq-orderby-on-ienumerablet – Paddy Apr 02 '14 at 10:01
  • sorry for not being clear and thanks for the link.. it seems to be advanced level of c# I am not exactly sure how I can pass `jtSoring` string parameter using those techniques. – pv619 Apr 02 '14 at 10:30
  • thanks for getting back :) - I tried your update and it seems to be loading but it's not doing it. I have updated my code above with your fix. – pv619 Apr 02 '14 at 10:50
  • You're still returning the list variable rather than the sorted variable. – Paddy Apr 02 '14 at 10:59
  • Looking at your code in more detail, if you just sort your datatable first (before making the list), then this should work... – Paddy Apr 02 '14 at 11:00
  • thanks Paddy - I removed the list and I have updated my code above.. man it still don't work. I'm lost! :( – pv619 Apr 02 '14 at 11:07
  • If I were you, I would start by tidying up your code - remove the list parts altogether, as you are not using them. Sort the default view on your datatable and use that. Tidying up the code should help you to sort out where you are going wrong as you debug through. – Paddy Apr 02 '14 at 13:00
  • yeah man that's one main thing that needs to be done properly. thanks.. :) – pv619 Apr 02 '14 at 13:09
-1

Pretty much everything in C# inherits from object, which has a ToString() method. Not everything provides a particularly useful implementation (some things just print their type name, particularly collections) but Int32 does. Therefore, i.Times.ToString() will give you the string version.

anaximander
  • 6,723
  • 3
  • 42
  • 62
  • 1
    _"some things just print their type name, particularly collections"_ _Everything_ returns it's fully qualified type name **which does not override ToString** since that is the default implementation of `object.ToString`. – Tim Schmelter Apr 02 '14 at 09:39
  • Well, yes. What I meant is that some things have a useful override, like `int`, and some things don't. With a question about something as basic as whether `int32` has a `.ToString()`, I thought it best not to get too complicated. – anaximander Apr 02 '14 at 09:43
-1

If you use Linq

daa.OrderByDescending(i => i.Times.ToString())
daa.OrderByDescending(i => (string)i.Times)

If you use Linq on EF

daa.OrderByDescending(i => SqlFunctions.StringFormat((double?)i.Times))
Michael Mairegger
  • 5,984
  • 27
  • 39
  • If an expression `x` is of type `int`, it cannot be converted to type `string` with a conversion expression (cast) `(string)x`. So one of your examples is illegal. The syntax `(string)x` is useful only if the compile-time type of `x` is a base class of `string` (that would be `object`) or some interface that `string` implements, and when you know that the run-time type of `x` is really going to be `string`. – Jeppe Stig Nielsen Apr 02 '14 at 11:19