AMIT SHELKE
AMIT SHELKE

Reputation: 533

Sort List<T> with integer property using C#

I want to sort my List, where T is Products. The List may contains elememts with duplicate ReportSeqId. I want to sort it according to ReportSeqId.

But the criteria is that if the ReportSeqId = 0 then it should come last.

INPUT :

new ilistProd<Products>()
{
    new Products(0, Report1, SSR),
    new Products(2, Report2, SBO),
    new Products(0, Report3, PST),
    new Products(3, Report4, ABR),
    new Products(1, Report5, OSS),
    new Products(0, Report6, TCP),
}

OUTPUT:

new ilistProd<Products>()
{
    new Products(1, Report5, OSS),
    new Products(2, Report2, SBO),
    new Products(3, Report4, ABR),
    new Products(0, Report3, PST),
    new Products(0, Report6, TCP),
    new Products(0, Report1, SSR)
}

Below is my code :

public class Products
{
    //ctor
    public SDVar(int xiReportSeqId, string xiReportName, string xiProduct)
    {
      this.ReportSeqId = xiReportSeqId;
      this.ReportName = xiReportName;
      this.Product = xiProduct;
    }

   public int ReportSeqId {get; set;}
   public string ReportName {get; set;}
   public string Product {get; set;}
}


public class SDVar
{
    //ctor
public SDVar()
{
}

public void DoSort(ref List<Products> ilistProd)
{
    ilistProd.Sort(delegate(Products x, Products y)
    {
        if (x.ReportSeqId == 0)
        {
            if (y.ReportSeqId == 0) 
            { 
                return 0; 
            }
            return -1;
        }
        return x.ReportSeqId.CompareTo(y.ReportSeqId);
    }       
}
 }

Upvotes: 0

Views: 130

Answers (4)

MrFox
MrFox

Reputation: 5116

Another way is to implement IComparable

public class Product : IComparable<Product>
{
    private int ReportSeqId = 0;

    public int CompareTo(Product other)
    {
        if (ReportSeqId == 0 || other == null) return 1;

        if (other.ReportSeqId == 0) return - 1;

        return ReportSeqId - other.ReportSeqId;
    }
}

Upvotes: 1

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73452

Try this

list.Sort(delegate(Products x, Products y)
{
    if(x.ReportSeqId == 0)
        return 1;       
    if(y.ReportSeqId == 0)
        return -1;
    return x.ReportSeqId.CompareTo(y.ReportSeqId);
}); 

Upvotes: 1

Me.Name
Me.Name

Reputation: 12544

Normally my preferred solution would be to add an extra property (e.g. SortIndex) which can be used in either Linq, or in a sort delegate (where id 0 would return an int.maxvalue), but to get the existing code to work, you should do an extra check to see of the second id is 0, if the first id is not:

if (x.ReportSeqId == 0)
{
    if (y.ReportSeqId == 0)
    {
        return 0;
    }
    return 1;
}
else if (y.ReportSeqId == 0) 
    return -1;
return x.ReportSeqId.CompareTo(y.ReportSeqId);

Upvotes: 1

amnezjak
amnezjak

Reputation: 2031

Using LINQ:

products = products.OrderBy(p => p.ReportSeqId == 0 ? Int32.MaxValue : p.ReportSeqId).ToList();

Upvotes: 0

Related Questions