Reputation: 47
How do I get items which equal to an input value from a generic list?
for example,
class Example {
string stringFiled;
string[] arrayFiled; // the length of array is fixed
}
Assumption: if the field name contains "array", it will be an array.
I have a generic filter function to filter the list by the field name and an input keyword.
Assume that we only care about index 1 when we access array field.
I only can finish partial function.
Could you help me to access the array property?
public List<T> Filter(List<T> src, string field, string keyword) {
if (field.Contains("array")) {
// Don't know how to do access the array property in generic list
} else {
list = list.where(x => x.GetType().GetProperty(field).GetValue(x).ToString().Contains(keyword)).Select(x => x).ToList();
}
return list;
}
Upvotes: 0
Views: 697
Reputation: 156469
List<T> Filter<T>(List<T> src, string field, string keyword)
{
var reflectedField = typeof(T).GetField(field);
var fieldType = reflectedField.FieldType;
if (fieldType.GetInterfaces().Contains(typeof(IEnumerable<string>)))
{
// Don't know how to do access the array property in generic list
return src.Where(x => ((IEnumerable<string>)reflectedField.GetValue(x)).Any(v => v.Contains(keyword))).ToList();
}
else
{
return src.Where(x => reflectedField.GetValue(x).ToString().Contains(keyword)).ToList();
}
}
IEnumerable<string>
(which includes arrays and lists), then it'll get picked up.Contains
criteria to ==
or Equals
..Select(x => x)
is always a no-op. Get rid of that dead code.Upvotes: 1