我有一个枚举如下:
IEnumerable<dynamic> collection = new
{
column1 = "1", column2 = "name", column3= "somevalue"
},
new
{
column1 = "2", column2 = "name2", column3= "somevalue2"
},
new
{
column1 = "3", column2 = "name3", column3= "somevalue3"
}
依此类推...动态类型中的列数也可以变化。列数可以多也可以少。
现在,如果我想搜索这个 IEnumerable 集合,例如somevalue2,我需要以下信息 位于列“column2”中的第 2 行(假设第 1 列始终是主键)。 这是将此动态集合转换为数据结构(.NET 列表/集合/哈希表等)的最佳方式,也是从集合中查询信息的最佳方式。该集合最多是一页数据(25 行)。 任何能够以超快速有效的方式搜索数据的代码片段和数据结构都将受到赞赏。假设搜索词是“包含”匹配而不是完美匹配。
最佳答案
这些是匿名类型;匿名类型是编译器功能,因此布局在编译时固定刚性,因此它们不会发生变化。我建议:不要使用dynamic
。例如:
var arr = new[] {
new { column1 = "1", column2 = "name", column3= "somevalue" },
new { column1 = "2", column2 = "name2", column3= "somevalue2" },
new { column1 = "3", column2 = "name3", column3= "somevalue3" }
};
都是强类型且定义明确的。您可以使用常规操作,例如:
var item2 = arr.FirstOrDefault(x => x.column1 == "2");
同样,所有静态类型。
如果你想搜索所有列,那么我建议像字典这样的东西更好:
var arr = new[] {
new Dictionary<string,string> { {"column1", "1"}, ... },
new Dictionary<string,string> { {"column1", "2"}, ... },
new Dictionary<string,string> { {"column1", "3"}, ... },
};
既然你可以看看 .Values.Contains(...)
编辑:有了我认为的评论,我理解得更清楚了;我正在想象一个返回 IEnumerable<dynamic>
的不透明方法。它们实际上是 POCO 类型(不是动态类型),我们想要检查字符串成员(任意名称)是否匹配。我们应该能够通过反射来做到这一点,但是FastMember会让它更快:
static void Main()
{
string search = "ame2";
int rowIndex = 0;
string[] names = null;
TypeAccessor accessor = null;
foreach(object row in GetData())
{
if(names == null)
{ // first row; get the property-names and build an accessor
names = (from prop in row.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)
where prop.PropertyType == typeof (string)
select prop.Name).ToArray();
accessor = TypeAccessor.Create(row.GetType());
}
foreach(var name in names)
{
var val = accessor[row, name] as string;
if(val != null && val.Contains(search))
{
Console.WriteLine("row {0}, col {1}, val {2}", rowIndex, name, val);
}
}
rowIndex++;
}
}
static IEnumerable<dynamic> GetData()
{
yield return new {column1 = "1", column2 = "name", column3 = "somevalue"};
yield return new {column1 = "2", column2 = "name2", column3 = "somevalue2"};
yield return new {column1 = "3", column2 = "name3", column3 = "somevalue3"};
}
关于c# - 搜索 IEnumerable<dynamic>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11852736/