SharkyShark
SharkyShark

Reputation: 380

is there a way to say LINQ that list is sorted...?

I'll have some big data in database and i need to group items by indexes, for example

data[0] = > property_1 = 'zxc', property_2='xxx'

in database i have record which looks like:

data[0]/property_1/zxc
data[1]/property_1/zzz
data[0]/property_2/xxx
data[3]/property_1/ooo

so i can sort them in database (it is fast, select statement get 1 second only) but if i want to grup them in linq it is very slow

important: for some reasons i can not grup them in database, i have to do it in application

Upvotes: 2

Views: 151

Answers (1)

Richard
Richard

Reputation: 109100

No. And Enumerable.GroupBy cannot make use of such knowledge.

But, as you know the input is sorted, you can write a less general GroupBy like method for your case where the assumption is made.

(But doing the group by on the database would be better.)

Such a custom group by, assuming in key order, would look something like:

IEnumerable<IGrouping<TKey, TElement>> InputOrderedGroupBy<T, TKey>(
                          this IEnumerable<T> input, 
                          Func<T, TKey> keyExtractor) {
  TKey currKey = default(TKey);
  Grouped<T, TKey> res = null;
  foreach (var t in input) {
    var thisKey = keyExtractor(t);
    if (res == null || thisKey != currKey) {
      if (res != null) {
        yield return res;
      }
      res = new Grouped<T, TKey>();
      res.Key = currKey = thisKey;
    }
    res.Collection.Add(t);
  }
  if (res != null) {
    yield return res;
  }
}

where Grouped<T, TKey> is some implemention of IGrouping<TKey, TElement>.

Upvotes: 3

Related Questions