0

I have generic list already filled with values, I need to sort items, that first value should appear same as query string. Is it possible to compare and sort this values, I'm trying with no success.

Bit updating my question.

For example I have Id: 1,2,3,4,5, and I opened page with Id=5, so I need on my searchResult, to pass 4 as first item in the list.

This code for me worked fine and showing 5 as first item, but I need to force for example p2.ObjectId pass as string value just for example "4294", and object with this Id should appear first:

Sort(searchresult);

   static void Sort(List<CollectionsItem> list)
        {
            list.Sort((p1, p2) => string.Compare(p2.ObjectId, p1.ObjectId, true));
        }
Renaldas
  • 45
  • 1
  • 9
  • 2
    What error are you getting with the posted code? How is it not what you are trying to accomplish? – StriplingWarrior Dec 08 '11 at 22:53
  • You are sorting your objects by their 'ObjectId' property. What do you mean by 'string value'? – muratgu Dec 08 '11 at 22:58
  • Take a look at this link and this SO question the third answer in the SO Question I think will help you. Link: http://www.singingeels.com/Blogs/Nullable/2008/03/26/Dynamic_LINQ_OrderBy_using_String_Names.aspx SO Question: http://stackoverflow.com/questions/722868/sorting-a-list-using-lambda-linq-to-objects – CBRRacer Dec 08 '11 at 23:00
  • Guys, I updated my question, thanks – Renaldas Dec 08 '11 at 23:19

2 Answers2

1

Doesn't sound like you want a sort at all.

If you want to put X at the top it's just

var item = MyList[MyList.IndexOf(Target)];
MyList.Remove(item);
MyList.Insert(item,0);

If you want Target at the top and the rest sorted by objectid

Find it, remove it, sort the rest and insert it at zero...

Tony Hopkinson
  • 19,528
  • 3
  • 29
  • 38
1

It sounds like you want to compare the value of the property ObjectId as a number instead of a string. Here is my suggestion:

        static void Sort(List<CollectionsItem> list)
        {
            list.Sort((p1, p2) =>
                {
                    if (int.Parse(p1.ObjectId) == int.Parse(p2.ObjectId))
                        return 0;
                    else if (int.Parse(p2.ObjectId) > int.Parse(p1.ObjectId))
                        return 1;
                    else
                        return -1;
                });
        }
Eric.K.Yung
  • 1,662
  • 11
  • 9