sahil sahil - 1 year ago 58
C# Question

c# rearranging class object based on property values?

The problem is :
We have model id as input parameter to a function and we need to shift that model id at the top among car that have luxury=false. The luxury car should remain at the same position.

class Car
int ModelId;
bool IsLuxury;

Sample car objects:

1. new Car(1, true)
2. new Car(19, true)
3. new Car(1, true)
4. new Car(7, true)
5. new Car(8, false)
6. new Car(9, false)
7. new Car(1, false)
8. new Car(25, false)
9. new Car(9, false)
10. new Car(1, false)

For example if input modelId=1, the list order should change like:

1. new Car(1, true)
2. new Car(19, true)
3. new Car(1, true)
4. new Car(7, true)
5. new Car(1, false)
6. new Car(1, false)
7. new Car(8, false)
8. new Car(9, false)
9. new Car(25, false)
10. new Car(9, false)

The cars with luxury=true remains at same rank [Rank 1 to 4],

the cars with modelId=1(input) and IsLuxury=false takes the next positions,

and other cars come in order subsequently (model not 1 and IsLuxury=false).

I want to code this in C#. I have a solution which returns me correct answer but i am not sure of its performance.

var res = lst.Where(c => c.IsLuxury== true)
.Concat(lst.Where(c => c.ModelId == 1 && c.IsLuxury== false))
.Concat(lst.Where(c => c.ModelId != 1 && c.IsLuxury== false)).ToList();

Can someone suggest some other way in c#, or using linq to achieve this in a better way?

Answer Source

You could do something like this, using IComparer<Car>:

class CarComparer : IComparer<Car>
    private int _sortModel;

    public CarComparer(int sortModel)
        _sortModel = sortModel;

    public int Compare(Car car1, Car car2)
        if (car1.IsLuxury)
            return car2.IsLuxury ? 0 : -1;
        else if (car2.IsLuxury)
            return 1;

        if (car1.ModelId == _sortModel)
            return car2.ModelId == _sortModel ? 0 : -1;
        return car2.ModelId == _sortModel ? 1 : 0;

And then you'd use it like this:

int modelToSortBy = 1;
var res = lst.OrderBy(c => c, new CarComparer(modelToSortBy));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download