3

希望能够填充对象的任何属性并在集合中搜索与给定属性匹配的对象。

class Program
{
    static List<Marble> marbles = new List<Marble> { 
        new Marble {Color = "Red", Size = 3},
        new Marble {Color = "Green", Size = 4},
        new Marble {Color = "Black", Size = 6}
    };

    static void Main()
    {
        var search1 = new Marble { Color = "Green" };
        var search2 = new Marble { Size = 6 };
        var results = SearchMarbles(search1);
    }

    public static IEnumerable<Marble> SearchMarbles(Marble search)
    {
        var results = from marble in marbles
                      //where ???
                      //Search for marbles with whatever property matches the populated properties of the parameter
                      //In this example it would return just the 'Green' marble
                      select marble;
        return results;
    }

    public class Marble
    {
        public string Color { get; set; }
        public int Size { get; set; }
    }

}
4

7 回答 7

5

诚然,这很有趣,需要我花时间。首先,您需要获取search与默认值不同的对象的所有属性,此方法是使用反射的通用方法:

var properties = typeof (Marble).GetProperties().Where(p =>
                {
                    var pType = p.PropertyType;
                    var defaultValue = pType.IsValueType 
                            ? Activator.CreateInstance(pType) : null;

                    var recentValue = p.GetValue(search);

                    return !recentValue.Equals(defaultValue);
                });

然后你可以使用 LINQAll来过滤:

var results = marbles.Where(m => 
                         properties.All(p => 
                         typeof (Marble).GetProperty(p.Name)
                                        .GetValue(m) == p.GetValue(search)));

ps:这段代码已经测试过了

于 2012-09-23T17:44:26.690 回答
2

You can use a separate Filter class like this:

class Filter
{
    public string PropertyName { get; set; }
    public object PropertyValue { get; set; }

    public bool Matches(Marble m)
    {
        var T = typeof(Marble);
        var prop = T.GetProperty(PropertyName);
        var value = prop.GetValue(m);
        return value.Equals(PropertyValue);
    }
}

You can use this Filter as follows:

var filters = new List<Filter>();
filters.Add(new Filter() { PropertyName = "Color", PropertyValue = "Green" });

//this is essentially the content of SearchMarbles()
var result = marbles.Where(m => filters.All(f => f.Matches(m)));

foreach (var r in result)
{
    Console.WriteLine(r.Color + ", " + r.Size);
}

You could use DependencyProperties to get rid of typing the property name.

于 2012-09-23T17:21:08.573 回答
2

我将提出适用于任意数量的属性和任何对象的通用解决方案。它也可以在 Linq-To-Sql 上下文中使用——它可以很好地转换为 sql。

首先,首先定义将测试给定值是否被视为非集合的函数,例如:

static public bool IsDefault(object o)
{
    return o == null || o.GetType().IsValueType && Activator.CreateInstance(o.GetType()).Equals(o);
}

然后,我们将有一个函数构造一个 Lambda 表达式,并针对search对象中所有设置属性的值进行测试:

static public Expression<Func<T, bool>> GetComparison<T>(T search)
{
    var param = Expression.Parameter(typeof(T), "t");

    var props = from p in typeof(T).GetProperties()
                where p.CanRead && !IsDefault(p.GetValue(search, null))
                select Expression.Equal(
                    Expression.Property(param, p.Name),
                    Expression.Constant(p.GetValue(search, null))
                );

    var expr = props.Aggregate((a, b) => Expression.AndAlso(a, b));
    var lambda = Expression.Lambda<Func<T, bool>>(expr, param);         
    return lambda;
} 

我们可以在任何地方使用它IQueryable

public static IEnumerable<Marble> SearchMarbles (Marble search)
{
    var results = marbles.AsQueryable().Where(GetComparison(search));
    return results.AsEnumerable();
}   
于 2012-09-23T22:47:33.037 回答
1

您可以在 Marbles 类中覆盖 equals

public override bool Equals(object obj)
    {
        var other = obj as Marble;

        if (null == other) return false;

        return other.Color == this.color && other.size == this.size; // (etc for your other porperties
    }

然后你可以搜索

return marbles.Where(m => search == m);
于 2012-09-23T17:01:51.137 回答
1

假设如果属性具有默认值(即Color == nullSize == 0),则该属性未填充:

var results = from marble in marbles
              where (marble.Color == search.Color || search.Color == null)
                 && (marble.Size == search.Size || search.Size == 0)
              select marble;
于 2012-09-23T16:52:00.443 回答
0

If you want to avoid targeting specific properties, you could use reflection. Start by defining a function that returns the default value of a type (see here for a simple solution, and here for something more elaborate).

Then, you can write a method on the Marble class, which takes an instance of Marble as a filter:

public bool MatchesSearch(Marble search) {
    var t = typeof(Marble);
    return !(
        from prp in t.GetProperties()
        //get the value from the search instance
        let searchValue = prp.GetValue(search, null)
        //check if the search value differs from the default
        where searchValue != GetDefaultValue(prp.PropertyType) &&
              //and if it differs from the current instance
              searchValue != prp.GetValue(this, null)
        select prp
    ).Any();
}

Then, the SearchMarbles becomes:

public static IEnumerable<Marble> SearchMarbles(Marble search) {
    return
        from marble in marbles
        where marble.MatchesSearch(search)
        select marble;
}
于 2012-09-23T17:52:45.267 回答
0

使用反射,此方法将适用于所有类型,无论它们包含多少或什么类型的属性。

将跳过任何未填写的属性(引用类型为空,值类型为默认值)。如果它找到两个不匹配的已填写属性,则返回 false。如果所有填写的属性都相等,则返回 true。

IsPartialMatch(object m1, object m2)
{
    PropertyInfo[] properties = m1.GetType().GetProperties();
    foreach (PropertyInfo property in properties)
    {
        object v1 = property.GetValue(m1, null);
        object v2 = property.GetValue(m2, null);
        object defaultValue = GetDefault(property.PropertyType);

        if (v1.Equals(defaultValue) continue;
        if (v2.Equals(defaultVAlue) continue;
        if (!v1.Equals(v2)) return false;
    }

    return true;
}

将其应用于您的示例

public static IEnumerable<Marble> SearchMarbles(Marble search)
{
    return marbles.Where(m => IsPartialMatch(m, search))
}

GetDefault() 是这篇文章中的方法,相当于 default(Type)

于 2012-09-23T17:31:46.660 回答