Dynamically create anonymous object from list values c#

冷暖自知 提交于 2019-12-01 08:39:20

问题


I have a list (or can be array) of strings that I want to dynamically create an anonymous object from. How do I do this?

var dataSet = new DataSet();
dataSet.ReadXml(@"");
var dataTable = dataSet.Tables[0];
var dataRow = dataTable.Rows[0];    

var keys = new List<string> {"Column1","Column2"};
var result = new {keys[0] = dataRow[keys[0]], keys[1] = dataRow[keys[1]]}

So that list named "keys" is going to be created outside this method and can contain 1 to many values. I tried creating a dictionary and looping through the list and adding key/value pairs to the dictionary but then I couldnt figure out how to convert the dictionary back to an anonymous type. I also experimented with the expando objects but that didn't seem to get me any farther.

I must be able to return an anonymous type as the result of this method will be using with the GroupBy clause of a LINQ query.

Here is the method I had to dynamically create the dictionary:

    public object Key(DataRow dataRow, List<String> keys)
    {
        var dictionary = new IDictionary<string, object>;
        foreach (string key in keys)
        {
            dictionary.Add(key, dataRow[key]);
        }
        return dictionary;
    }

Here is my LINQ query:

var duplicates = dataTable.AsEnumerable().GroupBy(r => Key(r, keys)).Where(c => c.Count() > 1).ToList();

The GroupBy clause works if I hardcode in an anonymous type from the Key() method. Basically I just need the GroupBy clause to be dynamically set based upon the values in the keys list.


回答1:


Stripping down your question, what you want is to be able to group a list of items based on a runtime property which could be composed of one or more properties of that item. In essence, it means you need a selector function (which is your Key method) that transforms an item into a key.

In order for GroupBy to work, it needs to be able to compare any two instances of the key to see if they're equal. This means the key needs to implement a meaningful Equals() method, or you need an IEqualityComparer implementation that does the work for you. In this case I wouldn't bother with creating a new Key, just write an Equality Comparer that can compare two DataRows directly:

var duplicates = dataTable
        .AsEnumerable()
        .GroupBy(r => r, new MyDataRowComparer(keys))
        .Where(c => c.Count() > 1)
        .ToList();


internal class MyDataRowComparer : IEqualityComparer<DataRow>
{
    private readonly string[] _keys;

    public MyDataRowComparer(string[] keys)
    {
        _keys = keys; // keep the keys to compare by.
    }

    public bool Equals(DataRow x, DataRow y)
    {
        // a simple implementation that checks if all the required fields 
        // match. This might need more work.
        bool areEqual = true;
        foreach (var key in _keys)
        {
            areEqual &= (x[key] == y[key]);
        }
        return areEqual;
    }

    public int GetHashCode(DataRow obj)
    {
        // Add implementation here to create an aggregate hashcode.
    }
}    


来源:https://stackoverflow.com/questions/24463750/dynamically-create-anonymous-object-from-list-values-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!