Reputation: 3624
I got this List :
private static List<Type> _AbstractTypes = new List<Type>();
and later in my project I got a string
that corresponds to a Type.FullName.
The thing is that I'd like to check if my string is contained in my List but I don't manage to avoid a loop usable :(
Im looking for something like :
_AbstractTypes.FullName.Contains(myString)
I am absolutely aware that my previous code is not compilable at all but that's the sort of thing im looking for ! Thanks in advance for any help
Upvotes: 0
Views: 164
Reputation: 11977
You can use Linq, but we are talking about loop-less construct here only, the code under the hood must do a loop, if you want to do it better, you could use HashSet<T>
.
Linq code could look like this:
_AbstractTypes.Any(t => t.FullName == myString);
HashSet<Type>
code could look like this:
var types = new HashSet<Type>();
types.Add(typeof(int)); //Fill it with types
types.Add(typeof(double));
//Check by getting types from their string name, you could of course also cache those types
Console.WriteLine("Contains int: " + types.Contains(Type.GetType(intName))); //True
Console.WriteLine("Contains float: " + types.Contains(Type.GetType(floatName))); //False
Upvotes: 6
Reputation: 12468
I think you can find out if a type is contained in your list that way:
if (_AbstractTypes.Contains(typeof(string)))
{
// Do Something
}
Upvotes: 0
Reputation: 93080
You can't avoid looping.
You can do (with looping behind the scenes):
bool check = _AbstractTypes.Any(item => item.FullName == myString);
Upvotes: 0
Reputation: 9770
You probably want something like this:
_AbstractTypes.Any(t=>t.FullName.Contains(myString))
Upvotes: 0
Reputation: 37710
This code :
bool result = _AbstractTypes.Any(t=>t.FullName == myString);
Should do the job.
It will test the predicate against all type until one is satisfied (true is returned), or none (false is returned).
Upvotes: 1
Reputation: 22389
If the list contains elements, you can do something like _AbstractTypes.First().GetType()
.
Upvotes: 0