4

Possible Duplicate:
C# generic list <T> how to get the type of T?

I have a list variable and I want to get the type of that list and cast a second variable to that type. For clarity I added the code below.

Currently I have the following:

return _ValueList.Any<FieldType>(x => x.Equals((FieldType)fieldValueObject));

I want to do something like this:

Type valueType = _ValueList.GetType();

return _ValueList.Any<FieldType>(x => x.Equals((valueType)fieldValueObject));

Any help will be appreciated.

Update:

A invalid cast exception is thrown when fieldValueObject is of type Int16 and I try to cast it to Int32.

Update 2:

I used the following solution:

        if (fieldValueObject.GetType() == typeof(Int16))
        {
            fieldValueObject = Convert.ToInt32(fieldValueObject);
        }
        return _ValueList.Any<FieldType>(x => x.Equals(fieldValueObject));

It is not pretty but it works.

Community
  • 1
  • 1
FreddieGericke
  • 539
  • 1
  • 5
  • 13
  • What is it that you're trying to accomplish ? Are you trying to filter a List of numbers with a string value ? Seeing the rest of the function would help. – Alex Jul 26 '12 at 10:51
  • I am trying to check if a value exist in a generic list. The value that I am testing for is retrieved from a db, and when I to cast it to the list type it throws an exception. – FreddieGericke Jul 26 '12 at 11:09

1 Answers1

1
public bool ContainsAny<T>(List<T> valueList, T fieldValueObject)
{
    return valueList.Any(x => x.Equals(fieldValueObject));
}

or

public bool ContainsAny<T>(List<T> valueList, object fieldValueObject)
{
    return valueList.Any(x => x.Equals((T)fieldValueObject));
}

Note that the second can throw an InvalidCastException.

Paul Fleming
  • 24,238
  • 8
  • 76
  • 113
  • Both these methods works fine, except when fieldValueObject is of type Int16 and I try to cast it to Int32. – FreddieGericke Jul 26 '12 at 09:23
  • @FreddieGericke If you absolutely must do a cast, consider using type converters. `(T)TypeDescriptor.GetConverter(typeof(T)).ConvertFrom(fieldValueObject);` – Paul Fleming Jul 26 '12 at 09:26