KRob
KRob

Reputation: 389

How to Sort a Generic Collection With a Where Clause

I am using an IEnumerable as the dataSource for a Repeater control. I need to sort the IEnumerable WHERE an entities property value equals a given value, then ORDER BY some other value. In other words, I want to sort an IEnumerable after some selected entity.

I am guessing I will have to implement the IComparer interface, but not sure where to start. Perhaps it could be as simple as having 2 IEnumerables; one with the entity I want displayed first, a second with the other entities, then concatenate them.

 Dim myEnumerable As IEnumerable(Of myEntity) = dbContext.myEntity

 myEnumerable.OrderBy(Function(x) x.propertyA **where x.propertyA = "value"**) _
    .OrderBy(function(x) x.propertyB)

For simplicity of an example, I will use an IEnumerable(of String)

  Dim myEnumerable As IEnumerable(Of String) = {"1", "2", "3", "40", "50"}

  myEnumerable.OrderBy(Function(x) where x = "3" Then Order By x.length)

I am looking for the resulting sort to be

Upvotes: 0

Views: 118

Answers (1)

Rahul Singh
Rahul Singh

Reputation: 21795

Try This:-

Dim query = myEnumerable.Where(Function(x) x = "3").Concat(myEnumerable.Where(Function(x) x <> "3").OrderBy(Function(x) x)).ToList()

C# Equivalent:-

var query = myEnumerable.Where(x => x == "3").Concat(myEnumerable.Where(x => x != "3").OrderBy(x => x)).ToList();

Upvotes: 1

Related Questions