4

我有一个从数据库返回的动态对象列表,如下所示:

IEnumerable<dynamic> list = _repository.All(whereClause);

然后我需要对该列表做的是获取数组中指定的每个列名的唯一值列表。所以是这样的:

List<string> columns = new string[] {"Col1","Col1"};

foreach(string column in columns)
{ 
    //get unique value for column and add them to some collection 
    list.Select().Where(???)
}

因为列表是动态的,我不确定如何根据列名进行选择。

任何人都可以帮忙吗

4

3 回答 3

2

使用帮助类通过名称动态访问属性怎么样(可以扩展为使用一些缓存):

public class ObjectUtils
{
    public static object GetPropertyByName(object obj, string name)
    {
        if (obj == null)
        {
            return null;
        }
        PropertyInfo propInfo = obj.GetType().GetProperty(name);
        if (propInfo == null)
        {
            return null;
        }
        object value = propInfo.GetValue(obj, null);
        return value;
    }
}

然后得到这样的数据:

List<dynamic> list = new List<dynamic>();
list.Add(new { Col1 = "AB", Col2 = 23 });
list.Add(new { Col1 = "CD", Col2 = 23 });
list.Add(new { Col1 = "AB", Col2 = 5 });
list.Add(new { Col1 = "EF", Col2 = 9 });

string[] columns = new string[] { "Col1", "Col2" };
foreach (string column in columns)
{
    var elems = list.Select(d => ObjectUtils.GetPropertyByName(d, column)).Distinct().ToList();
    // elems will be "AB", "CD", "EF" for Col1
    //           and 23, 5, 9 for Col2
}

如果无法编译,请确保添加对 Microsoft.CSharp 的引用

于 2012-04-12T12:29:14.693 回答
1

如果没有更多信息,我会尝试这样的事情:

List<dynamic> list = new List<dynamic>();
list.Add(new { a = "Col1", b = "b" });
list.Add(new { a = "Col2", b = "c" });
list.Add(new { a = "Col1", b = "c" });

string[] columns = new string[] { "Col1", "Col2" };

foreach (string column in columns)
{
    Console.WriteLine(column);
    //get unique value for column and add them to some collection 
    var select=list.Where((x) => { return x.a == column; }).Select(x=>x.b);
    select.ToList().ForEach((x) => { Console.WriteLine("{0}",x ); });
}
Console.Read();
于 2012-04-12T11:56:54.717 回答
-1

能:

foreach(string column in columns)
{ 
    list.Where(x => x == column);
    list.Distinct();
}

帮你?

但是你可以跳过 foreach 循环:

list = list.Where(x => colums.Contains(x));

有没有你的双胞胎:

list = list.Distinct();
于 2012-04-12T11:42:05.183 回答