Reputation: 861
I have a Observable Collection and an item of the collection has a tag (string) and a isChecked (boolean).
The User can select a tag to sort the list e.g. "event" and/or set the IsChecked.
The Ordering priority should work like this: 1) isChecked == true 2) tag equals the item tag 3) rest of the items sorted alphabetically by tag
I show the ObservableCollection in a ListBox through xaml. Any idea how this can be achieved?
EDIT: providing example for clarification:
item0: tag = "apple", isChecked = false;
item1: tag = "apple", isChecked = true;
item2: tag = "pineapple", isChecked = false;
item3: tag = "coconut", isChecked = true;
item4: tag = "cherry", isChecked = false;
string is: "cherry"
outcome: item1, item3, item4, item0, item2
Upvotes: 0
Views: 2392
Reputation: 4002
To be able to retrieve your conditions, I did the below.
// Retrieve an IQueryable for the colleciton with your specified conditions
var query = from c in collection
orderby c.IsChecked descending, c.Tag.Equals("cherry") descending, c.obsTag
select c;
// Clear the collection
collection = new ObservableCollection<myCollectionObject>();
// Replace the collection with your IQueryable results
foreach(myCollectionObject obj in query) {
collection.Add(obj);
}
If you want it all in one line:
collection = new ObservableCollection<obsCol>(from c in collection
orderby c.obsCheck descending, c.obsTag.Equals("cherry") descending, c.obsTag
select c);
Upvotes: 2
Reputation: 45096
That #2 is a little trickier.
For that you may need to have another Public Enumerable in code behind that builds that up in two steps.
OP please clarify what #2 is before I go down this path.
2 Tag equals the tag
3 Alphabetically by tag
Not clear at all. Three reference to tag.
Based on your comment need top build up the List in two sets
The problem statement does not reflect the comment.
You cannot expect people to read comments.
IsChecked = True and Tag = 'match'
then append
IsChecked = false or Tag != 'match' order by tag
Sorry I don't have time for the LINQ right now and to be honest you have not shown much effort on a good problem statement.
Upvotes: 0
Reputation: 62246
To be separated from the implementation not only of the UI but of the model too, you have to use CollectionViewSource
The concrete example of how to sort the list of objects via some custom Comprarer, can be found here:
WPF: ListCollectionView for sorting, filtering and grouping
Upvotes: 1