0

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

Guillaume Slashy
  • 3,554
  • 8
  • 43
  • 68
  • So you don't want to use a loop? or you just want help implementing a loop? Because i think with a foreach loop you will get the desired result. – stackr Dec 07 '11 at 08:56

6 Answers6

6

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
Marcin Deptuła
  • 11,789
  • 2
  • 33
  • 41
1

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).

Steve B
  • 36,818
  • 21
  • 101
  • 174
0

If the list contains elements, you can do something like _AbstractTypes.First().GetType().

Ilya Kogan
  • 21,995
  • 15
  • 85
  • 141
0

You probably want something like this:

_AbstractTypes.Any(t=>t.FullName.Contains(myString))
Doron Yaacoby
  • 9,412
  • 8
  • 48
  • 59
0

You can't avoid looping.

You can do (with looping behind the scenes):

bool check = _AbstractTypes.Any(item => item.FullName == myString);
Petar Ivanov
  • 91,536
  • 11
  • 82
  • 95
0

I think you can find out if a type is contained in your list that way:

if (_AbstractTypes.Contains(typeof(string)))
{
    // Do Something
}
Fischermaen
  • 12,238
  • 2
  • 39
  • 56