简体   繁体   English

OrderByDescending 导致我的 datagridview 不填充

[英]OrderByDescending is causing my datagridview to not populate

I want to order my list based on the column HitCount.我想根据列 HitCount 对我的列表进行排序。 When I append OrderByDescending to the end of the source, the DataGridView is no longer being populated.当我 append OrderByDescending到源的末尾时,不再填充 DataGridView。 I can take it off and it works fine.我可以把它取下来,效果很好。

  var source = CapturedLogs.CapturedIpAddresses.OrderByDescending(x => x.HitCount);
  dataGridView1.DataSource = source;

  public static List<CapturedLog> CapturedIpAddresses{set;get;}

  internal class CapturedLog
  {
    public string IpAddress { set; get; }
    public int HitCount { set; get; }
    public bool IsRecordedInFirewall { set; get; }
    public bool IsWhiteListed { set; get; }

  }

When I add the .OrderByDescending(x => x.HitCount);当我添加.OrderByDescending(x => x.HitCount); the DataGridView doesn't populate. DataGridView 不填充。

What am I doing wrong?我究竟做错了什么?

As per the documentation , the DataSource property can only be set to an object of a type that implements IList , IListSource , IBindingList , or IBindingListView .根据文档DataSource属性只能设置为实现IListIListSourceIBindingListIBindingListView的类型的 object。

When you simply append .OrderByDescending() and don't actually materialize the result, it returns an object of type OrderedEnumerable , which does not implement any of the interfaces mentioned above.当您只是 append .OrderByDescending()并且实际上没有具体化结果时,它会返回 object 类型的OrderedEnumerable ,它实现上述任何接口。

You need to change the type of source to something that implements of the supported interfaces.您需要将source类型更改为实现支持接口的类型。 For example:例如:

// List<CapturedLog>
var source = CapturedLogs.CapturedIpAddresses
    .OrderByDescending(x => x.HitCount)
    .ToList();

// CapturedLog[]
var source2 = CapturedLogs.CapturedIpAddresses
    .OrderByDescending(x => x.HitCount)
    .ToArray();

// BindingSource
var ordered = CapturedLogs.CapturedIpAddresses.OrderByDescending(x => x.HitCount);
var source3 = new BindingSource(ordered, null);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM