【问题标题】:Check for a unique value inside a collection using LINQ?使用 LINQ 检查集合中的唯一值?
【发布时间】:2011-08-05 10:47:33
【问题描述】:

我有以下类定义:

public class PriorityItem
{
    public string uniqueID { get; set; }
    public List<DelegationTask> DelegationTasks = new List<DelegationTask>();
    public List<int> Priorities = new List<int>(); 
}

现在假设我从这个类创建一个列表,如下所示:

List<PriorityItem> pItems = new List<PriorityItem>();

现在我想根据 uniqueID 属性检查此列表中是否存在项目,这是如何完成的?

例如,我将使用 PriorityItem 集合填充列表,但前提是 Priority 项目不存在。要确定它是否存在,我需要使用 LINQ 检查 uniqueID 的值。

希望这是有道理的。

【问题讨论】:

    标签: linq


    【解决方案1】:

    如果找到任何符合特定条件的项目,Any linq 扩展方法将返回 true。您可以按如下方式使用它:

    string idToSearchFor = "123"
    bool exists = pItems.Any(item => item.uniqueId == idToSearchFor);
    

    只有当您的列表包含PriorityItemuniqueId"123" 时,上述代码exists 才会为真。

    【讨论】:

    • 谢谢,这正是我想要的!
    【解决方案2】:

    Exists 与 Any 做同样的事情。 Exists 比 Any 更符合 SQL 用语。 Any 和 All 作为一种自然限定符pair自然地结合在一起。

    但是在句子中,“我们有这个唯一的 id 吗?”就可读性和意图而言,也许“存在”更合适。

    class Class1
    {
        [Test]
        public void Test()
        {
            // initialise list
            var pItems = new List<PriorityItem>(){new PriorityItem(){uniqueID = "1"}, new PriorityItem(){uniqueID = "2"}, new PriorityItem(){ uniqueID = "123"}};
            var IDtoFind = "123";
            var wasFound = pItems.Exists(o => o.uniqueID == IDtoFind);
        }
    }
    
    public class PriorityItem
    {
        public string uniqueID { get; set; }
        //public List<DelegationTask> DelegationTasks = new List<DelegationTask>();
        public List<int> Priorities = new List<int>();
    
    }
    

    【讨论】:

      猜你喜欢
      • 2010-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-26
      • 2020-01-28
      • 1970-01-01
      相关资源
      最近更新 更多