【问题标题】:Trying to get a list of properties dynamically where count > 0尝试动态获取计数> 0的属性列表
【发布时间】:2016-05-24 18:02:19
【问题描述】:

我有一个这样的模型

public class UserModel
{
    List<UserModel> users
}
public class UserModel
{
    public List<UserSomeObj> userSomeObj { get; set; }
    public List<UserSomeOtherObj> userSomeOtherObj { get; set; }
}
public class UserSomeObj
{
    public int someIntProperty { get; set; }
    public string someStringProperty { get; set; }
}
public class UserSomeOtherObj
{
    public int someIntProperty { get; set; }
    public string someStringProperty { get; set; }
}

每个 UserModel 类 List 都由几个其他类 List 组成。

我通过循环遍历目标属性列表来动态引用它们。

获取与“prop”变量匹配的属性列表;

var props = MethodToGetTargetedProperties(); 
// props example content would be a list of strings like so "UserSomeObj", "UserSomeOtherObj"
foreach (var prop in props)
{
    var results = users.Select(x => x.GetPropertyValue(prop)).ToList();
    //results contain lists of prop where count == 0 and i dont want them
}

我想要做的是减少目标列表计数大于 0 的结果......问题是我找不到正确的顺序/语法来让它工作。

谢谢

【问题讨论】:

    标签: c# model-view-controller model


    【解决方案1】:

    谢谢.....在查看您的回复时,我能够做到以下几点

    var results = users.Select(x => x.GetPropertyValue(prop))
        .Cast<IEnumerable<object>>().Where(y => y.Count() > 0).ToList();
    

    然后在更多地查看您的答案并尝试理解其所有方面之后,我想知道我是否可以在一行中完成所有操作。 UserModel 中的两个 List 类有 2 个共同的属性(idSomething 和 idSomeOtherThing),因为我将把它们组合起来做一个 Distinct,我想,嗯,一个衬里可能是可能的。

    【讨论】:

    • 如果你转换为IEnumerable而不是ICollection,你应该使用.Any()而不是.Count() &gt; 0
    【解决方案2】:

    由于List&lt;T&gt; 实现了非泛型 ICollection 接口,您可以转换为:

    var results = users.Select(x => x.GetPropertyValue(prop))
                       .Cast<ICollection>()
                       .Where(list => list.Count > 0)
                       .ToList();
    

    如果你愿意,你可以在 Where 中进行演员表,虽然我更喜欢上面的:

    var results = users.Select(x => x.GetPropertyValue(prop))
                       .Where(list => ((ICollection) list).Count > 0)
                       .ToList();
    

    【讨论】:

    • 为什么不直接转换为ICollection 并检查Count 属性?我打赌你有充分的理由,我只是想从你的回答中学习。谢谢
    • @blins:啊,非泛型ICollection。是的,我喜欢它。我不能使用ICollection&lt;T&gt;,因为这在T 中不是协变的,但List&lt;T&gt; 也实现了ICollection...是的,将编辑:)
    • 在更多地查看您的答案并尝试了解其所有方面之后,我想知道我是否可以在一行中完成所有操作。 UserModel 中的两个 List 类有 2 个公共属性(idSomething 和 idSomeOtherThing),因为我将把它们组合起来做一个 Distinct,我想,嗯,一个衬里可能是可能的。
    • @user3071434:好吧,如果不了解您在做什么,很难说...但是您可以使用SelectMany 选择多个属性,然后过滤...
    猜你喜欢
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    • 1970-01-01
    • 2016-09-20
    • 1970-01-01
    • 2012-10-27
    • 2020-05-11
    • 1970-01-01
    相关资源
    最近更新 更多