简体   繁体   中英

OrderByDescending is causing my datagridview to not populate

I want to order my list based on the column HitCount. When I append OrderByDescending to the end of the source, the DataGridView is no longer being populated. 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); the DataGridView doesn't populate.

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 .

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.

You need to change the type of source to something that implements of the supported interfaces. 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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