F.C. Hsiao
F.C. Hsiao

Reputation: 47

Access the element of array property in a generic list via C# LINQ

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

Answers (1)

StriplingWarrior
StriplingWarrior

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();
    }
}
  • I'm assuming you intend to get fields rather than properties, but it would be relatively easy to change this code to get properties, or even to handle both properties and fields.
  • Rather than requiring the name to follow a specific pattern, this will be based on the declared type of the field. If it implements IEnumerable<string> (which includes arrays and lists), then it'll get picked up.
  • I'm assuming you want this to match an item in the list where any of the strings in the array field contain the keyword. If you want them to be equal to the keyword, change the Contains criteria to == or Equals.
  • .Select(x => x) is always a no-op. Get rid of that dead code.

Upvotes: 1

Related Questions