c# - 尝试从 linq 正在创建的(匿名类)对象获取属性/字段

标签 c# .net linq

我无法弄清楚我在这里做错了什么。我有一些 LINQ 返回 IQuery对象,稍后在代码中,我尝试列出返回的属性。这个缩写代码可以最好地解释这一点(实际的 LINQ 要复杂得多,并且涉及连接 - LINQ 本身工作得很好):

public IQueryable<Object> FindAll()
{
    var query = from user in _db.Users
    select new
    {
        id = user.Id,
        is_active = user.IsActive,
        email = user.Email,
        dob = user.Dob,
        user.user_type,
    };
    return query;
}

我的代码中的其他地方:

query.ConvertToCsv();

尽管我尝试插入 .ToList()也在该通话中。

ConvertToCsv有:

public static string ConvertToCSV<TSource>(this IEnumerable<TSource> source)
{
    StringBuilder sb = new StringBuilder();

    var properties = typeof(TSource).GetFields(BindingFlags.NonPublic | BindingFlags.Instance);

    var enumerable = source as IList<TSource> ?? source.ToList();
    if (!enumerable.Any()) return "";

    string headerString = "";

    foreach (var prop in properties)
    {
        headerString += (headerString.Length > 0 ? "," : "") + prop.Name;
    }
    sb.AppendLine(headerString);

    foreach (TSource item in enumerable)
    {
        string line = string.Join(",", properties.Select(p => p.GetValue(item).ToCsvValue()).ToArray());
        sb.AppendLine(line);
    }

    return sb.ToString();
}

注意,我还尝试使用以下代码提取属性名称:

PropertyInfo[] pi = typeof(TSource).GetProperties(BindingFlags.Public | BindingFlags.Instance);
var properties = pi.OrderBy(x => x.MetadataToken);
foreach (PropertyInfo p in properties)
{ etc etc }

在所有情况下,属性或字段列表都会返回空列表,因此,我无法迭代对象以吐出标题行或数据行。跟踪所有代码并检查变量表明一切都很好,直到我到达 GetProperties/GetFields行并且代码失败。

我犯了什么菜鸟错误?我应该更换<Object>还有别的东西吗?

最佳答案

To pass an anonymous type, or a collection that contains anonymous types, as an argument to a method, you can declare the parameter as type object. However, doing this defeats the purpose of strong typing. If you must store query results or pass them outside the method boundary, consider using an ordinary named struct or class instead of an anonymous type.

作者:Anonymous Types (C# Programming Guide)

创建您自己的类并将方法声明更改为 IQueryable<MyClass>而不是object

关于c# - 尝试从 linq 正在创建的(匿名类)对象获取属性/字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18334099/

相关文章:

c# - 自定义 Linq 扩展语法

xml - 使用 LINQ to XML 将 HTML 标记保留在 XML 中

c# - 正则表达式替换所有出现的地方

c# - 读取嵌入式 XML 文件 C#

.net - WPF,设计器中的 'Object reference not set to an instance of an object'

.net - 如果我只有 Type 实例,如何调用泛型方法?

C# HTTP Post代码导致工作进程挂起

c# - LINQ to XML 在 xml 中查找特定类别

c# - WEB API & BL关系

c# - 一个单词并打印它的不同 3 个字母组合