简体   繁体   English

通过 C# LINQ 访问通用列表中数组属性的元素

[英]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.我有一个通用过滤器 function 通过字段名称和输入关键字过滤列表。

Assume that we only care about index 1 when we access array field.假设我们在访问数组字段时只关心索引 1。

I only can finish partial function.我只能完成部分 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;
 }
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.我假设您打算获取fields而不是properties ,但是更改此代码以获取 properties 甚至处理 properties 和 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.如果它实现了IEnumerable<string> (其中包括 arrays 和列表),那么它将被拾取。
  • 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 .如果您希望它们等于关键字,请将Contains条件更改为==Equals
  • .Select(x => x) is always a no-op. .Select(x => x)始终是无操作的。 Get rid of that dead code.摆脱那些死代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM