从动态列表中获取唯一的值列表

时间:2012-04-12 11:38:41

标签: c# linq

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

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(???)
}

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

任何人都可以帮忙吗

3 个答案:

答案 0 :(得分: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的引用

答案 1 :(得分: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();

答案 2 :(得分:-1)

可以:

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

帮助你?

但是你可以跳过foreach循环:

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

并且你有小册子:

list = list.Distinct();