Reputation: 31
In essence I have function which takes arguments : ContainsValue(IEnumerable collection, object obj)
And I need to check if collection Contains
obj with the use of Equals().
Specifically collection is an array of strings and obj is a custom type/class (Its called FString, I dont completely understand what it is but it is at least somewhat derivative from string).
Unfortunately the solution needs to be generic so I cant explicitly reference the custom type.
And so I need a way to generically cast obj into whatever type the collection is. Is this possible?
EDIT:
static bool ContainsValue(IEnumerable collection, object obj)
{
// cast obj into same type as collection elements
foreach(var element in collection)
{
if() // element equals obj
{
return true;
}
}
return false;
}
Upvotes: 1
Views: 130
Reputation: 52280
And so I need a way to generically cast obj into whatever type the collection is. Is this possible?
If that is your only question then the solution is easy. Please edit your question if you need something more than this.
static bool ContainsValue<T>(IEnumerable<T> collection, object obj) where T : class
{
var compareTo = obj as T;
if (obj == null) return false; //Return false if cast was not possible
foreach (var item in collection)
{
if (item == obj) return true;
}
return false;
}
You could also force the caller to do the cast, which seems like a smarter way to go about it, since then you can enforce type safety at compile time. Also you can shorten the code with a tiny bit of LINQ.
static bool ContainsValue<T>(IEnumerable<T> collection, T obj) where T : class
{
return collection.Any( item => item == obj );
}
Upvotes: 0
Reputation: 31721
Use IEnumerable
's OfType method to extract the target type you are looking for and if there are some check the equality situation you mentioned...such as this example
return collection.OfType<string>()
.Any( str => str.Equals("Jabberwocky"));
Upvotes: 0
Reputation: 6528
You can use it like this (if you can access fields of the collection):
string objAsString = obj?.ToString() ?? "";
if(collection.Any(x => x.field == objAsString))
{
//Do something...
}
Upvotes: 0
Reputation: 38880
You should just be able to use this in your if
statement:
if(object.Equals(element, obj))
and then you don't need to cast at all, or worry about nulls, etc.
Upvotes: 2
Reputation: 35155
The details are quite vague but Enumerable.Cast(IEnumerable) Method
may help.
Doco, with an example, here.
System.Collections.ArrayList fruits = new System.Collections.ArrayList(); fruits.Add("mango"); fruits.Add("apple"); fruits.Add("lemon"); IEnumerable<string> query = fruits.Cast<string>().OrderBy(fruit => fruit).Select(fruit => fruit); // The following code, without the cast, doesn't compile. //IEnumerable<string> query1 = // fruits.OrderBy(fruit => fruit).Select(fruit => fruit); foreach (string fruit in query) { Console.WriteLine(fruit); } // This code produces the following output: // // apple // lemon // mango
Upvotes: 0