Home > Back-end >  OrderByDescending is causing my datagridview to not populate
OrderByDescending is causing my datagridview to not populate

Time:03-10

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?

CodePudding user response:

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);
  • Related