循环LINQ查询列(而不是行)

flvtvl50  于 2024-01-03  发布在  其他
关注(0)|答案(3)|浏览(182)

是否可以循环遍历LINQ查询的结果?如果可以,如何循环遍历LINQ查询的结果?
就像这样:

  1. var results= from a in dt.AsEnumerable()
  2. where a.Field<int>("id") == i
  3. select new
  4. {
  5. id= a.Field<int>("id"),
  6. a= a.Field<double>("a"),
  7. b = a.Field<double>("b")
  8. };
  9. IEnumerable<string> colNames = results.First().GetType().GetProperties()
  10. .Select(p => p.Name);
  11. string[] columns = colNames.ToArray();
  12. int i = 0;
  13. foreach (var row in results)
  14. {
  15. for (int i = 0; i < columns.Count(); i++)
  16. {
  17. string foobar = (string)row[columns[i]];
  18. i++;
  19. }
  20. }

字符串
基本上,我想复制以下功能:

  1. DataRow dr = new DataRow();
  2. string foobar = dr[columns[i];

jei2mxaa

jei2mxaa1#

如果您可以选择更改原始LINQ语句以生成一个数据结构,从而实现您所期望的功能,我绝对建议您这样做。
如果没有,你需要使用反射来查找匿名类型的属性,然后通过反射获取这些属性的值:

  1. PropertyInfo[] columns = results.First().GetType().GetProperties();
  2. ...
  3. string foobar = columns[i].GetValue(row, null);

字符串

zengzsys

zengzsys2#

  1. Action<string> processColumName = (cname) =>
  2. {
  3. // do anything you want with a column name
  4. string foo = (string) Row[cname];
  5. };
  6. results.First()
  7. .GetType()
  8. .GetProperties()
  9. .Select(p => p.Name)
  10. .ToList().ForEach(processColumName);

字符串

yzckvree

yzckvree3#

好吧,我的答案实际上是基于另一个问题的stovroz答案,略有修改:
代码如下:

  1. foreach(var item in db.Products) {
  2. System.Reflection.PropertyInfo[] fields = Product.GetType().GetProperties();
  3. foreach(var f in fields) {
  4. Console.WriteLine(f.Name + ": " + f.GetValue(item));
  5. }
  6. }

字符串

相关问题