I have inherited a VB application and am looking for converting some things to C# (part of migration). I have an extension method in VB that is like this:
<Extension()>
Public Function ContainsAnyOf(Of T)(SourceList As List(Of T), ParamArray ParamList() As T) As Boolean
If SourceList IsNot Nothing AndAlso ParamList IsNot Nothing Then
For Each ParamItem As T In ParamList
If SourceList.Contains(ParamItem) Then Return True
Next
End If
Return False
End Function
I have translated it to C# as follows:
public static bool ContainsAnyOf<T>(this List<T> sourceList, IEnumerable<T> parameters)
{
if (parameters.Count() == 0 || sourceList == null || sourceList.Count < 1)
{
return false;
}
else
{
foreach (var parameter in parameters)
{
if (sourceList.Contains(parameter))
return true;
else
return false;
}
return false;
}
}
To be complete, the model is declared in a separate cs-file as follows:
public class TestModel
{
public int Id { get; set; }
public string ModelValue1 { get; set; }
public string ModelValue2 { get; set; }
public bool ModelBool { get; set; }
}
In a testapplication (console) I have following testcode:
var testAnyOf = false;
var testElement = new List<string>(){ "Test 2", "Testje 2" };
if (model.ContainsAnyOf(testElement))
{
testAnyOf = true;
}
Console.WriteLine($"Does the list contains the {testElement}? Outcome = {testAnyOf}");
Console.ReadLine();
But I get a compiler error CS0411: The type arguments for method 'ListExtensions.ContainsAnyOf(List, IEnumerable)' canot be inferred from the usage ...
I know that what the Error means but I have tried few things now but still don't know how to pass the 'Parameters'.
Eventually what I need is like in the original VB application and that works like:
bool isInList = alistOfModel.ContainsAnyOf("One", "Dog", "Hat")
I think the first part with the List of type T is correct but how to pass the parameters.. Thanks!
That should compile if
modelis of typeList<string>. I assume thatmodelis of some other type.However, I would implement this using Linq like so (likely to be much more performant):
You could also use
paramsso that you can call it with an argument list of items to match:Using the latter, instead of writing
You could write