1

I have a LINQ query that looks like this:

 var p = option.GetType().GetProperties().Where(t => t.PropertyType == typeof(bool));

What is the most efficient way to get the items which aren't included in this query, without executing a second iteration over the list.

I could easily do this with a for loop but I was wondering if there's a shorthand with LINQ.

13
  • A for loop is an iteration too.
    – Bauss
    Aug 21, 2015 at 13:29
  • var p2 = option.GetType().GetProperties().Where(t => t != typeof(bool)); or var p2 = option.GetType().GetProperties().Where(i => !p.Contains(i));
    – Fabio
    Aug 21, 2015 at 13:29
  • 2
    @Fabio: Isn't this another query which OP doesn't want? Aug 21, 2015 at 13:30
  • 2
    @FabioLuz that's another iteration Aug 21, 2015 at 13:30
  • Do you want all the items that aren't included in that query? That's pretty simple -- var p = option.GetType().GetProperties() Aug 21, 2015 at 13:30

3 Answers 3

10
var p = option.GetType().GetProperties().ToLookup(t => t.PropertyType == typeof(bool));

var bools = p[true];

var notBools = p[false];

.ToLookup() is used to partition an IEnumerable based on a key function. In this case, it will return an Lookup which will have at most 2 items in it. Items in the Lookup can be accessed using a key similar to an IDictionary.

.ToLookup() is evaluated immediately and is an O(n) operation and accessing a partition in the resulting Lookup is an O(1) operation.

Lookup is very similar to a Dictionary and have similar generic parameters (a Key type and a Value type). However, where Dictionary maps a key to a single value, Lookup maps a key to an set of values. Lookup can be implemented as IDictionary<TKey, IEnumerable<TValue>>

.GroupBy() could also be used. But it is different from .ToLookup() in that GroupBy is lazy evaluated and could possibly be enumerated multiple times. .ToLookup() is evaluated immediately and the work is only done once.

7
  • Great , I guess it's a good time for me to get familiat wit ToLookup :P Aug 21, 2015 at 13:33
  • But isn't under the hood there are 2 queries: one for bools and one for notBools? Usage is pretty though.
    – Sinatr
    Aug 21, 2015 at 13:34
  • No, there is not two queries, only one. ToLookup() iterates over the list once and based on the evaluation of the expression, adds the current item to either the true list or false list. ToLookup() executes immediately, just like ToList().
    – kmc059000
    Aug 21, 2015 at 13:35
  • 1
    Haven't seen this answer before i posted mine. However, note that t == typeof(bool) never is true because a PropertyInfo is never a bool. Aug 21, 2015 at 13:44
  • I see now. ToLookup() will execute query over GetProperties() once and result will be stored in some structure p (lookup). Then p[true] and p[false] only does query over that new structure, which obviously avoid iterating over option.GetType().GetProperties() again and is much more efficient. New day - something new to learn.
    – Sinatr
    Aug 21, 2015 at 13:44
2

You cannot get something that you don't ask for. So if you exlude all but bool you can't expect to get them later. You need to ask for them.

For what it's worth, if you need both, the one you want and all other in a single query you could GroupBy this condition or use ToLookup which i would prefer:

var isboolOrNotLookup =  option.GetType().GetProperties()
    .ToLookup(t => t.PropertyType == typeof(bool)); // use PropertyType instead

Now you can use this lookup for further processing. For example, if you want a collection of all properties which are bool:

List<System.Reflection.PropertyInfo> boolTypes = isboolOrNotLookup[true].ToList();

or just the count:

int boolCount = isboolOrNotLookup[true].Count();

So if you want to process all which are not bool:

foreach(System.Reflection.PropertyInfo prop in isboolOrNotLookup[false])
{

}
1
  • Yeah, familiarity with ToLookUp was the key part in solving this with LINQ. Aug 21, 2015 at 13:39
-2

Well, you could go for source.Except(p), but it would reiterate the list and perform a lot of comparisons.

I'd say - write an extension method that does it using foreach, basically splitting the list into two destinations. Or something like this.

How about:

public class UnzipResult<T>{
    private readonly IEnumearator<T> _enumerator;
    private readonly Func<T, bool> _filter;

    private readonly Queue<T> _nonMatching = new Queue<T>();
    private readonly Queue<T> _matching = new Queue<T>();

    public IEnumerable<T> Matching {get{
        if(_matching.Count > 0)
            yield return _matching.Dequeue();
        else {
            while(_enumerator.MoveNext()){
            if(_filter(_enumerator.Current))
                yield return _enumerator.Current;
            else 
                _nonMatching.Enqueue(_enumerator.Current);
            }
            yield break;
        }
    }}

    public IEnumerable<T> Rest {get{
        if(_matching.Count > 0)
            yield return _nonMatching.Dequeue();
        else {
            while(_enumerator.MoveNext()){
            if(!_filter(_enumerator.Current))
                yield return _enumerator.Current;
            else 
                _matching.Enqueue(_enumerator.Current);
            }
            yield break;
        }
    }}

    public UnzipResult(IEnumerable<T> source, Func<T, bool> filter){
        _enumerator = source.GetEnumerator();
        _filter = filter;
    }
}

public static UnzipResult<T> Unzip(this IEnumerable<T> source, Func<T,bool> filter){
    return new UnzipResult(source, filter);
}

It's written in notepad, so probably doesn't compile, but my idea is: whatever collection you enumerate (matching or non-matching), you only enumerate the source once. And it should work fairly well with those pesky infinite collections (think yield return random.Next()), unless all elements do/don't fulfil filter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.