1

I have a large list of objects, the object contains things like string name, string address, string city.

I want to create a findEqualsMatch method like this.. where it takes in a string called varName, and then searches the variable of the object which varName is called.

that way if i do data.FindEquals("name", "tom") it searches the objects "name" property to be equal to tom, at the same time you can write "address" and it will search the address property.

public List<Datum> FindEquals(String varName, String value)
            {
                List<Datum> results = new List<Datum>();
                foreach (Datum result in data)
                {
                    //should search for address variable
                    // instead of if(result.Address == value)

                    if (result.varName == value)
                        results.Add(result);

                }

                return results;
            }

List<Datum> newResults = data.FindEquals("address", "123 street");

the whole purpose is to query a set of factual API results and return a set that is searched on by any variable type you insert into the function.

mathERSI
  • 66
  • 3
  • What are you searching for? value or varName? – Vivin Feb 11 '15 at 02:55
  • I am searching for value, of the variable from varName inside of an object... does that clearify? that way if i do data.FindEquals("name", "tom") it searches the objects "name" property to be equal to tom, at the same time you can write "address" and it will search the address property. – mathERSI Feb 11 '15 at 02:56
  • You'd have to use reflection (see below), or better/faster/type-safe is to replace `String varName` by a matcher delegate. – tofi9 Feb 11 '15 at 04:24

1 Answers1

1

You can use reflection. Starting from Get property value from string using reflection in C# your sample will look like:

public List<Datum> FindEquals(String varName, String value)
        {
            List<Datum> results = new List<Datum>();
            var propertyInfo = (typeof Datum).GetProperty(varName);
            foreach (Datum result in data)
            {
                String varValue = (string)propertyInfo.GetValue(result, null);
                if (varValue == value)
                    results.Add(result);
            }
            return results;
        }

Alternatively you can use Func<string, Datum> as field accessor arguments or corresponding Expression tree similar to LINQ-to-SQL (i.e. Get the property name used in a Lambda Expression in .NET 3.5)

Community
  • 1
  • 1
Huy Hoang Pham
  • 3,972
  • 1
  • 13
  • 26