使用Linq到C#获取特定的属性值

时间:2012-06-13 12:07:12

标签: c# linq

我创建了一个具有此类属性的类

public class Dependencies
{
    public string issueID { get; set; }
    public string status { get; set; }
    public int dependencyCheck { get; set; }
}

现在我创建了一个可以使用这些属性的方法。

private static void prepareIssuesList(string IssueKey, string JIRAtoken)
{
    Dependencies dpObj = new Dependencies();
    List<Dependencies> listObj = new List<Dependencies>();
    dpObj.issueID = IssueKey;
    dpObj.status = "open";
    dpObj.dependencyCheck = 0;
    listObj.Add(dpObj);

}

现在我的问题是,如何更改dependencyCheck属性值。 prepareIssuesList()可以多次调用。所以我在Dependencies类中添加了多个对象。在某些时间点我想更改dependencyCheck属性值。这该怎么做。我认为需要使用Linq来C#。 ICan任何人都有这个解决方案吗?

1 个答案:

答案 0 :(得分:4)

我会沿着这些方向做点什么:

public class Dependency
{
     public string IssueId { get; set; }
     public string Status { get; set; }
     public int DependencyCheck { get; set; }
}

public class DependencyManager
{
     public DependencyManager()
     {
          this.Dependencies = new List<Dependency>();
     }         

     public List<Dependency> Dependencies { get; private set; }

     public void AddDependency(string issueId)
     {
         var dep = new Dependency();
         dep.IssueId = issueId;
         dep.Status = "open";
         dep.DependencyCheck = 0;

         this.Dependencies.Add(dep);
     }

     public void SetDependencyCheck(string issueId, int value)
     {
         var dep = this.FindDependencyByIssueId(issueId);
         dep.DependencyCheck = value;
     }

     public Dependency FindDependencyByIssueId(string issueId)
     {
         var dep = this.Dependencies.FirstOrDefault(d => d.IssueId.Equals(issueId));
         if(dep == null) throw new ArgumentException("Dependency not found", "issueId");
         return dep;
     }
}

然后你可以在代码中的某个地方执行:

var mgr = new DependencyManager();
mgr.AddDependency("ABC123");
mgr.AddDependency("ABC456");

//... some other stuff that makes sense

mgr.SetDependecyCheck("ABC123", 42);