score:-1

Can:

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

Help you?

But then you can skip the foreach loop:

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

and have you duplets:

list = list.Distinct();

score:1

Without more info I would try something like this:

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();

score:2

What about using a helper class to dynamically access the properties by name (could be extended to use some caching):

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;
    }
}

And then get the data like this:

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
}

If it doesn't compile, make sure to add a reference to Microsoft.CSharp


Related Articles