简体   繁体   中英

Converting a List of String Type To Decimal Type List

I Have a List<MyClass> MyList
Where MyClass Description is

 public class MyClass
    {
        public Nullable<decimal> Id { get; set; }
        public string Marks { get; set; }
        public string rank { get; set; }
    }

Items in MyList

Id  Marks Rank
1   100   null
2   15    null
3   5     null
4   55    null
5   51    null
6   12    null
7   32    null

Here Type Of Mark s Is String Therefore If I try To Sort/OrderBy It by Marks It Gives me wrong Sort order
Is There any Way From which i convert the type Of Marks Column From String --> Decimal

You'd have to prepare another class, with proper property type:

public class MyClass2
{
    public Nullable<decimal> Id { get; set; }
    public decimal Marks { get; set; }
    public string rank { get; set; }
}

Then you can use LINQ to convert one list into another:

var newList = source.Select(x => new MyClass2
                                 {
                                     Id = x.Id,
                                     Marks = decimal.Parse(x.Marks),
                                     rank = x.rank
                                 }).ToList();

Or you can do the ordering without changing the property:

var orderedList = source.OrderBy(x => decimal.Parse(x.Marks)).ToList();

Change the property of mark to decimal

public class MyClass
{
    public Nullable<decimal> Id { get; set; }
    public decimal Marks { get; set; }
    public string rank { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM