Mike
Mike

Reputation: 3284

Match two collections dynamically by a criteria

I have a collection of filter criteria objects with each criteria having a name (data object property name) and value property. I have another collection (my data objects) and I need to filter this collection to return data objects which matches the filter criteria.The properties are string values so there is no worry on the type. How can I do this?

Below is the code:

public class FilterCriteria
    {
        public string ColumnName { get; set; }

        public string ColumnValue { get; set; }
    }

  public class DataObject
    {
        public string Name { get; set; } 
    }



public static void Match()
        {
            var criteria1 = new FilterCriteria() {ColumnName = "Name", ColumnValue = "abc"};
            var criteria2 = new FilterCriteria() { ColumnName = "Name", ColumnValue = "xyz" };
            var criteriaCollection = new List<FilterCriteria> {criteria1, criteria2};

            var data1 = new DataObject() {Name = "xyz"};
            var data2 = new DataObject() { Name = "abc" };
            var data3 = new DataObject() { Name = "def" };
            var dataCollection = new List<DataObject> {data1, data2, data3};

            //filter datacollection by the criterias, match any data object with Name property equal to column value
            //After the matching I will get the result as data1 & data2.
        }

Thanks, -Mike

NOTE:The FilterCriteria will be serialized to disk using xml serialization.

Upvotes: 2

Views: 176

Answers (1)

Konrad Kokosa
Konrad Kokosa

Reputation: 16898

To get property from its name stored in string you have to use Reflection, for example:

DataObject someDataObject = ...;
typeof(DataObject).GetProperty("SomePropertyName").GetValue(someDataObject)

Then, combining it with LINQ:

var filtered = dataCollection.Where(obj => 
                    criteriaCollection.Any(cond => obj.GetType()
                                                      .GetProperty(cond.ColumnName)
                                                      .GetValue(obj)
                                                      .Equals(cond.ColumnValue)))
                             .ToList();

Upvotes: 1

Related Questions