C# - Troubles with IEnumerable.Where - c#

I'm currently working on a little program, which should get the information scanned by a barcode scanner (a so-called "HID") via the Raw-Input API.
I've read many tutorials about that and i think I'm understanding how it works. I'm using an IEnumerable to enumerate the input-devices. But now the compiler screams that the Where-Method is not known for an IEnumerable.
I've going through the MSDN-Articles regarding the IEnumerable and if I have understand the articles right, the Where-Method should be part of it.
Below a little snippet with the place i want to use the Where:
var rawInputDevice in rawDeviceEnumerator.Devices
.Where(d => d.DeviceType == Win32.RawInputDeviceType.Keyboard)
Can someone please give me an approach?
I think its just a little thing I'm overseeing.

The problem you are noting typically comes from older Collection types before .net 3.0, which introduced generic types.
The method you want to use is Enumerable.Where(this IEnumerable<T> enumerable, Func<T,bool> predicate). However rawDeviceEnumerator.Devices seems to be an IEnumerable and NOT IEnumerable<T>. Assuming you are using the RawInputDeviceEnumerator from http://www.news2news.com/vfp/?example=571&ver=vcs&PHPSESSID=5f4393ed0b6c7c205851a834e657e8be, then you have several options.
First. Change the code from
public IEnumerable Devices
{
get
{
return this._devices;
}
}
To
public IEnumerable<RawInputDevice> Devices
{
get
{
return this._devices;
}
}
Or you can use
var rawInputDevice in rawDeviceEnumerator.Devices
.Cast<RawInputDevice>()
.Where(d => d.DeviceType == Win32.RawInputDeviceType.Keyboard)

I think you mean Enumeration.Where which is an extension method. It appears to 'add' methods to existing classes bases on the type of the class and it's base classes or interfaces.
If you include System.Linq as namespace in your code files, you will see this extension method will appear on every object that implements IEnumerable<TSource>, for example List<T> or int[].

Related

Get the classes from another project [duplicate]

Is there a better (more performant or nicer code ;) way to find all derived Types of a Type?
Currently im using something like:
get all types in used Assemblies
check my type with all those types if it is 'IsAssignable'
I was wondering if theres a better way todo this?
I once used this Linq-method to get all types inheriting from a base type B:
var listOfBs = (
from domainAssembly in AppDomain.CurrentDomain.GetAssemblies()
// alternative: from domainAssembly in domainAssembly.GetExportedTypes()
from type in domainAssembly.GetTypes()
where typeof(B).IsAssignableFrom(type)
// alternative: && type != typeof(B)
// alternative: && ! type.IsAbstract
// alternative: where type.IsSubclassOf(typeof(B))
select type).ToArray();
EDIT: As this still seems to get more rep (thus more views), let me add a fluent version and some more details:
var listOfBs = AppDomain.CurrentDomain.GetAssemblies()
// alternative: .GetExportedTypes()
.SelectMany(domainAssembly => domainAssembly.GetTypes())
.Where(type => typeof(B).IsAssignableFrom(type)
// alternative: => type.IsSubclassOf(typeof(B))
// alternative: && type != typeof(B)
// alternative: && ! type.IsAbstract
).ToArray();
Details:
As the above-mentioned link states, this method uses Reflection on each call. So when using the method repeatedly for the same type,
one could probably make it much more efficient by loading it once.
As Anton suggests, maybe you could (micro)optimize it using domainAssembly.GetExportedTypes()
to retrieve only publicly visible types (if that's all you need).
As Noldorin mentions, Type.IsAssignable will also get the original (non-derived) type. (Type.IsSubclassOf will not, but Type.IsSubclassOf will not work if the base type is an interface). But of course, one can exclude the original base class: && type != typeof(B).
One may want/need to check for a concrete implemented class, i.e. ignore abstract classes: && ! assemblyType.IsAbstract. (Note that all interfaces are considered abstract, see MSDN.)
FWIW: as Jon Skeet suggested in a similar question: "it is trickier if you need to handle generics".
A quick search returns some suggestions, but there are probably more, and I did not check them (e.g. for correctness):
Get all types implementing specific open generic type
Get all implementations types of a generic interface
Getting all types that implement an interface
I'm pretty sure the method you suggested is going to be the easier way to find all derived types. Parent classes don't store any information about what their sub-classes are (it would be quite silly if they did), which means there's no avoiding a search through all the types here.
Only recommendation is to use the Type.IsSubclassOf method instead of Type.IsAssignable in order to check whether a particular type is derived from another. Still, perhaps there is a reason you need to use Type.IsAssignable (it works with interfaces, for example).
The only optimization you can squeeze out of this is to use Assembly.GetExportedTypes() to retrieve only publicly visible types if that's the case. Other than that, there's no way to speed things up. LINQ may help with readability side of things, but not performance-wise.
You can do some short-circuiting to avoid unnecessary calls to IsAssignableFrom which is, according to Reflector, quite expensive one, by first testing whether the type in question is of required "class". That is, you're searching for classes only, there's no point in testing enums or arrays for "assignability".
I think there is no better or direct way.
Better: Use IsSubclassOf instead of IsAssignable.
Asuming baseType contains a System.Type object that you want to check against and matchType contains a System.Type object with the type of your current iteration (through a foreach-loop or whatever):
If you want to check wheather matchType is derived from the class represented by baseType I'd use
matchType.IsSubclassOf(baseType)
And if you want to check wheather matchType implements the interface represented by baseType I'd use
matchType.GetInterface(baseType.ToString(), false) != null
Of course I'd store baseType.ToString() as a global variable so I wouldn't need to call it all the time. And since you probably would need this in a context where you have a lot of types, you could also consider using the System.Threading.Tasks.Parallel.ForEach-Loop to iterate through all your types...
If you're just interested in browsing, then .NET Reflector has the ability to do this. However, it isn't something that's really feasible. Would you want all types that are in the currently loaded assemblies? Assemblies referenced by the executing assembly? There are many different ways to obtain a list of Types, and writing something that would account for (and provide options for) would be a pretty big cost with relatively low benefit.
What are you trying to do? There's likely a better (or at least more efficient) way to accomplish it.
I ended up using the code that the top answer gave. Only thing is I wanted the code to be more readable so I wrote basically the same thing but like this instead:
var derived_types = new List<Type>();
foreach (var domain_assembly in AppDomain.CurrentDomain.GetAssemblies())
{
var assembly_types = domain_assembly.GetTypes()
.Where(type => type.IsSubclassOf(typeof(MyType)) && !type.IsAbstract);
derived_types.AddRange(assembly_types);
}
In my case I used type.IsSubClassOf(MyType) because I only wanted derived types excluding the base class like mentioned above. I also needed the derived types not to be abstract (!type.IsAbstract) so I am also excluding derived abstract classes.
Just create a static dictionary of derived types on start and do lookup with that.
Eg. public static Dictionay<Type, Type[]> DerivedTypes { get;set; }
where Type is any type you want to include in the search
and Type[] is a list of derived types.
Fill the dictionary up when app starts and use it during the whole life of the app.

Does usage of contains on IEnumerable cast it to a List?

I'm using Linq to filter Data I get from the database. Due to design choices made 1 method returns me an IEnumerable<int> which I then use for a linq statement to see which IDs are permitted to be returned (code follows below). My question here is as I'm not seeing anything there in the documentation: Does the Contains method implicitly cast the IEnumerable to a List for the statement to be executed? (If so the question is if using List in the first place instead of IEnumerable is better).
Code Example
private List<MyData> GetAllPermittedData()
{
IEnumerable<int> permitteddIds = GetPermittedIDs();
return (from a in MyDataHandler.GetAllData() where permittedIds.Contains(a.Id)
select a);
}
Like I asked above I'm not sure if the Contains part implicitly converts permittedIds into a List<int> (for/inside the use of the Contains statement). If this is the case then a followup question would be if it is not better to already use the following statement instead (performance-wise):
private List<MyData> GetAllPermittedData()
{
List<int> permitteddIds = GetPermittedIDs().ToList();
return (from a in MyDataHandler.GetAllData() where permittedIds.Contains(a.Id)
select a);
}
The LINQ operator will attempt to cast it to ICollection<T> first. If the cast succeeds, it uses that method. Since List<T> implements this interface, it will use the list's contain method.
Note that if you use the overload that accepts an IEqualityComparer, it must iterate over the enumerable and the ICollection shortcut is not taken.
You can see this implementation in the .NET Framework reference source:
public static bool Contains<TSource>(this IEnumerable<TSource> source, TSource value) {
ICollection<TSource> collection = source as ICollection<TSource>;
if (collection != null) return collection.Contains(value);
return Contains<TSource>(source, value, null);
}
Jon Skeet also has a good (and lengthy) blog series called "Reimplementing LINQ" where he discusses the implementation in depth. He specifically covers Contains in part 32 of his blog.
The Contains method may try to cast the passed IEnumerable<T> to IList<T> or to ICollection<T>. If the cast succeeds, it may directly use the methods of IList<T>, otherwise it will enumerate over the full sequence.
Note that I am writing may because this is implementation-specific and it is not specified in the docs. As such, it could be different across .NET versions and also in alternative implementations such as Mono.
Your advantage by providing only an IEnumerable<T> is that you have more freedom to exchange the object returned from that property without changing the public interface. The performance cost of the attempted cast to IList<T> or similar should be negligible.
In any case, this way is more performant than your suggestion of calling ToList, as that will actually create a new List<T> and copy all items from the enumeration into it.
Contains exists as an extension method for IEnumerable<T>. But you con't need to convert your IEnumerable to a List<T> with ToList(), you could simply use that IEnumerable<T> to fill a HashSet<T>:
var permitteddIds = new HashSet<int>(GetPermittedIDs());

Concise syntax to invoke instance methods after invoking LINQ methods

I have a type that wraps an IEnumerable<T> and contains some additional logic, implementing an interface which we'll call IMyIterable<T>. On one hand, I want people to use LINQ methods to filter and process IMyIterable<T> (by actually applying them to the underlying object), but on the other hand, I still want to fluently expose IMyIterable<T>'s custom instance functionality (e.g state information) after the LINQ methods have been applied. e.g.
var query = myIterable.Select(x => x.whatever);
//query is now of a completely different type than IMyIterable<T>
var result = query.MyCustomThingy();
//But I really want MyCustomThingy to work too.
I know a solution would be:
var query = myIterable.Linq(x => x.Select(y => y.Whatever));
But the extra brackets are unseemly to me. Are there any other ways I could do this? I'm not actually asking for the method Select() to return a custom class (though if there are neat ways to do this, e.g. involving code generation, I'm definitely aboard), just some neater syntax.
LINQ is not tied to IEnumerable. You can implement the LINQ methods you need on IMyIterable itself (either as instance methods or as extension methods). This way you can even use the linq syntax directly on a variable of type IMyIterable.
E.g.:
public interface IMyIterable<T>
{
IMyIterable<TOut> Select<TOut>(Func<T, TOut> selector);
IMyIterable<T> Where(Func<T, bool> predicate);
// ...
}
This would allow you to write something like this:
IMyIterable<T> source = ...;
var query = from item in source
where item.X == Y
select new {...}
Could you implement the methods on IMyIterable as extension methods to IEnumerable instead ? Not knowing exactly what this interface does makes it hard to come up with a solution.
Instead of deriving from IEnumerable, you could create a bunch of equivalent methods on IMyIterable (returning IMyIterable) and forward them to the inner IEnumerable instance.
However this seems like a lot of work to go around a cast. I guess your suggested .Linq() solution would work OK.

Why can Enumerable.Except be used on a string array in C#?

Example
Here is a code example I found at the Pete on Software blog:
var listThree = new string[] { "Pete", "On", "Software" };
var listFour = new string[] { "Joel", "On", "Software" };
stringExcept = listThree.Except(listFour);
The code compiles and runs. So far so good.
Question
However, I don't understand why it works.
So, can anyone explain why I can use Enumerable.Except on a string array?
Perhaps, it will be clear to me if someone could explain how to read the signature of Enumerable.Except and give me a code example:
public static IEnumerable<TSource> Except<TSource>(
this IEnumerable<TSource> first,
IEnumerable<TSource> second
)
What I know
I know the concepts of generics and extension methods. But obviously not good enough to understand the code example above. I have also already used some basic Linq queries.
Except is an extension method which extends any type that implements IEnumerable<T>. This includes the System.Array type which implements IEnumerable<T>.
The note on the linked page explains why the docs don't show System.Array implementing IEnumerable<T>
In the .NET Framework version 2.0, the Array class implements the System.Collections.Generic.IList<T>, System.Collections.Generic.ICollection<T>, and System.Collections.Generic.IEnumerable<T> generic interfaces. The implementations are provided to arrays at run time, and therefore are not visible to the documentation build tools. As a result, the generic interfaces do not appear in the declaration syntax for the Array class, and there are no reference topics for interface members that are accessible only by casting an array to the generic interface type (explicit interface implementations). The key thing to be aware of when you cast an array to one of these interfaces is that members which add, insert, or remove elements throw NotSupportedException.
It just says that if you have an IEnumerable of a given type TSource in this case string you can Except it with another IEnumerable of the same type and get a third IEnumerable of the same type back. The key point is that the two IEnumerable inputs have to be the same (and obviously the return will be of the same type).
An array of T (or say a T[]), is also an IEnumerable<T>. In your question, T is System.String. And Enumerable.Except is an extension method on IEnumerable<T>, so it's also working for a string[]. And stringExcept = listThree.Except(listFour); equals to
stringExcept = Enumerable.Except(listThree, listFour).
The compiler will match the TSource argument to string as a string array implements the IEnumerable<string> interface and thus matches the first argument of the extension method. So the answer is two things:
string[] implements IEnumerable<string>
The compiler is intelligent enough to infer the generic arguments
The Except method returns the elements in the first enumerable that do not also appear in the
second enumerable. So in the case you specified, the result would be {"Pete", "Joel"}.
In this case, thinking in terms of string arrays is perhaps a red herring. It might be more advantageous to think in terms of object equality (http://msdn.microsoft.com/en-us/library/system.object.equals.aspx).
The Microsoft documentation is here: http://msdn.microsoft.com/en-us/library/system.linq.enumerable.except.aspx

What is the "< >" syntax within C#

I have been learning about the basics of C# but haven't come across a good explanation of what this is:
var l = new List<string>();
I don't know what the <string> is doing or if it's the List that is doing the magic. I have also seen objects been thrown within the < > tags.
Can someone explain this to me with examples, please?
That is the generic syntax for C#.
The basic concept is that it allows you to use a Type placeholder and substitute the actual real type in at compile time.
For example, the old way:
ArrayList foos = new Arraylist();
foos.Add("Test");
worked by making ArrayList store a list of System.Objects (The base type for all things .NET).
So, when adding or retrieving an object from the list, The CLR would have to cast it to object, basically what really happens is this:
foos.Add("Test" as System.Object);
string s = foos[1] as String.
This causes a performance penalty from the casting, and its also unsafe because I can do this:
ArrayList listOfStrings = new ArrayList();
listOfStrings.Add(1);
listOfStrings.Add("Test");
This will compile just fine, even though I put an integer in listOfStrings.
Generics changed all of this, now using Generics I can declare what Type my collection expects:
List<int> listOfIntegers = new List<int>();
List<String> listOfStrings = new List<String>();
listOfIntegers.add(1);
// Compile time error.
listOfIntegers.add("test");
This provides compile-time type safety, as well as avoids expensive casting operations.
The way you leverage this is pretty simple, though there are some advanced edge cases. The basic concept is to make your class type agnostic by using a type placeholder, for example, if I wanted to create a generic "Add Two Things" class.
public class Adder<T>
{
public T AddTwoThings(T t1, T t2)
{
return t1 + t2;
}
}
Adder<String> stringAdder = new Adder<String>();
Console.Writeline(stringAdder.AddTwoThings("Test,"123"));
Adder<int> intAdder = new Adder<int>();
Console.Writeline(intAdder.AddTwoThings(2,2));
For a much more detailed explanation of generics, I can't recommend enough the book CLR via C#.
It's generics - it's a form of type parameterisation. In your example, it's making l refer to a list of strings - the list will only ever contain strings: the compiler treats it (pretty much) as if everywhere that the API docs mention "T" it actually says "string". So, you can only add strings to it, and if you use the indexer you don't need to cast to string, etc.
To be honest, giving generics detailed coverage on an online forum is pretty much impossible. (In C# in Depth, I take nearly 50 pages talking about generics.) However, armed with the name of the feature, you should be in a much better position to find out more. The MSDN "Introduction to C# Generics" is probably a good starting point.
Asking specific questions about generics on SO is likely to yield good results - I just don't think it can really be covered properly in one question/answer.
This is .NET Generics. The type within the < > denotes the type of element contained in the list.
with ArrayList you'd have to cast the elements inside...
int x = (int)myArrayList[4];
with List you can avoid that step because the compiler already knows the type.
int x = myList[4];
Generics are available in .NET 2.0 and later.
Those are generics. You are making a List that only contains strings. You could also say
List<int>
and get a list that only contains ints.
Generics is a huge topic, too big for a single answer here.
Those are known as Generics (specifically List is a generic class).
Reading from MSDN
Generics (C# Programming Guide)
An Introduction to C# Generics
Generics in the .NET Framework
This is generics in action. A regular List stores items of type Object. This requires casting between types. This also will allow you to store any kind of item in one instance of a list. When you are iterating through items in that list you cannot be sure that they are all of a certain type (at least not without casting each item). For instance lets say you create a list like this:
List listOfStrings = new List();
Nothing prevents someone from doing something like this:
listOfStrings.add(6); //Not a string
A generic list would allow you to specify a strongly-typed list.
List<string> listOfStrings = new List<string>();
listOfStrings.add("my name"); //OK
listofStrings.add(6); //Throws a compiler error
There is a more thorough examples on here Generics
< > is for generics. In your specific example, it means that the List is a List of strings, not say a list of ints.
Generics are used to allow a type to be, well, generic. It's used ALOT in Collections to allow them to take different types so that they can function much like a normal array and still catch invalid types being assigned at compile time. Basically it allows a class to say "I need to be associated with some specific type T, but I don't want to hard code exactly what that type is, and let the user select it.". A simple array for instance might look something like:
public class MyArray<T> {
private T[] _list;
public MyArray() : this.MyArray(10);
public MyArray(int capacity)
{ _list = new T[capacity]; }
T this[int index] {
get { return _list[index]; }
set { _list[index] = value; }
}
}
Here, we have a private list of type T that is accessed by using our class like a normal array. We don't care what type it is, it doesn't matter to our code. But anyone using the class could use it as, say MyArray<string> to create a list of strings, while someone else might use it as MyArray<bool> and create a list of flags.

Categories

Resources