如何重新排序CollectionViewSource?

时间:2016-05-05 09:50:09

标签: c# wpf datagridview collectionviewsource

我刚收到一些这样的数据

{
    "ID":2,
    "NOTAMRec":"C16-0001",
    "DeliverDate":"310827",
    "BeginDate":"1601010130",
    "ExpireDate":"1606070630",
    "Priority":"GG",
    "ItemA":"LOL",
    "OriginalNotamID":2,
    "SelectedNotamColor":null
},
{
    "ID":8,
    "NOTAMRec":"C16-0004",
    "DeliverDate":"230705",
    "BeginDate":"1602231505",
    "ExpireDate":"1606312359 EST",
    "Priority":"GG",
    "ItemA":"LOVEU",
    "OriginalNotamID":8,
    "SelectedNotamColor":null
},
{
    "ID":9,
    "NOTAMRec":"C16-0005",
    "DeliverDate":"240703",
    "BeginDate":"1602241502",
    "ExpireDate":"1606312359 EST",
    "Priority":"GG",
    "ItemA":"LOVEU",
    "OriginalNotamID":9,
    "SelectedNotamColor":null
}

我的模特

public Class MyModel 
{
  public long ID {get;set;}
  public string NOTAMRec {get;set;}
  public string ItemA {get;set;}
}

并将其添加到ObservableCollection中。

然后new CollectionViewSource().Source = theObservableCollection

问题 - 我想按此顺序对ViewSource进行排序,并将其显示在DataGridView中。

无论我在此集合中添加了多少MyModel, ItemA等于" LOVEU" 的模型将​​始终位于此列表的顶部

因此,当我向用户显示此列表时,他们将始终首先看到MyModelsLOVEU

谢谢!

3 个答案:

答案 0 :(得分:0)

Cagaya Coper试试这个

   var query = from c in theObservableCollection
                 orderby  c.ItemA.Equals("LOVEU") descending , c.ID
                 select c; 
new CollectionViewSource().Source = query 

Sorting ObservableCollection by String

答案 1 :(得分:0)

你可以试试这个

 var order = yourCollection.OrderByDescending(y => y.ItemA.IndexOf("LOVEU"));
  

这将根据属性进行排序名称此处为Name,默认情况下将按升序排序

修改 请在此处查看完整代码dotnetfiddle

答案 2 :(得分:0)

另一个建议是,使用事件排序并修改订单。

 grid.DataContext = ObservableCollection.OrderByDescending(y => y.ItemA.IndexOf("LOVEU")); 

 private void grid_Sorting(object sender, DataGridSortingEventArgs e)
    {
        ListCollectionView view = (ListCollectionView)(CollectionViewSource.GetDefaultView(this.DataContext));
        if (e.Column != null && e.Column.CanUserSort == true && e.Column.Header.ToString() != "ItemA")
        {
            var dgSender = (DataGrid)sender;
            var cView = CollectionViewSource.GetDefaultView(dgSender.ItemsSource);

            cView.SortDescriptions.Clear();
            cView.SortDescriptions.Add(new SortDescription("ItemA", ListSortDirection.Descending));

            if (e.Column.SortDirection == ListSortDirection.Ascending)
            {   
                e.Column.SortDirection = ListSortDirection.Descending;
                cView.SortDescriptions.Add(new SortDescription(e.Column.Header.ToString(), ListSortDirection.Descending));
            }
            else
            {   
                e.Column.SortDirection = ListSortDirection.Ascending;
                cView.SortDescriptions.Add(new SortDescription(e.Column.Header.ToString(), ListSortDirection.Ascending));
            }

            e.Handled = true;
        }

    }