tags:

views:

68

answers:

2

I have a list of news unsorted items, some of which have a priority flag. I need the priority items to float to the top of the list, and then sort the rest by a date.

So, the end result is a list of news items that has the priority items showing at the top and the remainder sorted by date.

There has to be a better way to do it than this but I'm not sure what the best way would be -

foreach (var newsItem in newsItems)
{
    if (newsItem.isPriority)
    {
        addToPriorityList(newsItem);
    }
    else
    {
        addToOtherList(newsItem);
    }
}

foreach (var priorityItem in priorityList)
{
    addtoMainList(priorityItem);
}

OtherList.SortbyDate();
foreach (var otherItem in otherList)
{
    addtoMainList(otherItem);
}

Is there a more elegant way to pull this off? I assume I could use LINQ but I'm very new to it so I'm not comfortable with the syntax.

+2  A: 

You should be able to do:

newsItems.OrderBy(item => item.Priority).ThenBy(item => item.Date);
Jackson Pope
@Jackson: you were the first
Vlad
Thanks, that's what I was looking for. I'm getting an exception - "At least one object must implement IComparable" but I'm assuming that it's because the values are stored as strings, i.e. - Date - "20101017T000000", IsPriority "0" or "1" The values are coming from a CMS
Will S
+2  A: 

Try this: (edited according to the suggestion in the 1st comment)

var sorteditems = newsItems.OrderByDescending(item => item.IsPriority)
                           .ThenBy(item => item.Date);
Vlad
The first order-by should be descending.
Eric Mickelsen
@Eric: indeed, thanks!
Vlad
@Will: Strange, strings implement IComparable in C#: http://msdn.microsoft.com/en-us/library/system.string.aspx. What is the type of `item.Date`?
Vlad
@Vlad: Also a string. In the CMS, the date is stored as "20101017T00000"
Will S
@Vlad: Aha, bug on my part - was looking to field object instead of the value. Thanks for jogging my brain!
Will S
That's double strange. Look at my example at http://ideone.com/oPoar, which runs perfectly. Could you try the same example in your program?
Vlad
Okay, it works. Nice!
Vlad