2010-08-11 58 views
1

我想使用泛型類短我的代碼,因爲如何使用泛型類通過linq編寫有用的代碼?

1)GetMaintData(INT任務id)RelTypeId和RefMaintenance
2)GetAliSpReqs(INT任務id)RelTypeId和RefAliSpReq

如果你看看下面的方法你只能看到TypeId和Ref數據。我認爲,我可以寫通過泛型類新的明確的代碼那樣:

http://www.thereforesystems.com/dynamic-sort-with-linq/

public void GetData<TKey>(List<TaskRelation> cities, Func<TaskRelation, TKey> selector) 
     { 
//include all GetMaintData,GetAliSpReqs,GetZone,GetAccess 
     }
public class EngGetCalculatedTaskField 
    { 
     private static TaskMaintenanceDataDataContext engTaskCtx { get; set; } 

     public EngGetCalculatedTaskField() 
     { 
      engTaskCtx = new TaskMaintenanceDataDataContext(); 
     } 
     public string GetMaintData(int taskID) 
     { 
       var query = engTaskCtx.TaskRelations.Where(r => r.TaskId == taskID && 
        r.RelTypeId == 12).Select(r => r.RefMaintenance.shortdesc); 
       return string.Join("; ", query.ToArray()); 
     } 
     public string GetAliSpReqs(int taskID) 
     { 
      var query = engTaskCtx.TaskRelations.Where(r => r.TaskId == taskID 
              && r.RelTypeId == 13) 
           .Select(r => r.RefAliSpReq.shortdesc); 
       return string.Join("; ", query.ToArray()); 
     } 
     public string GetAccess(int taskID) 
     { 
      var query = engTaskCtx.TaskRelations.Where(r => r.TaskId == taskID 
            && r.RelTypeId == 15) 
         .Select(r => r.RefAccessPanel.shortdesc); 
      return string.Join("; ", query.ToArray()); 
     } 
     public string GetZone(int taskID) 
     { 
      var query = engTaskCtx.TaskRelations.Where(r => r.TaskId == taskID 
            && r.RelTypeId == 14) 
         .Select(r => r.RefZone.shortdesc); 
      return string.Join("; ", query.ToArray()); 
     }

回答

1

事情是這樣的:

public string GetList(IEnumerable<TaskRelation> relations, 
         int taskId, int relTypeId, 
         Func<TaskRelation, string> projection) 
{ 
    var query = relations.Where(r => r.TaskId == taskId && 
            r.RelTypeID == relTypeId) 
         .Select(projection)); 
         .ToArray() 
    return string.Join("; ", query.ToArray()); 
} 

然後使用它是這樣的:

string zones = GetList(reslations, taskID, 14, r => r.RefZone.shortdesc); 

請注意,我已經假定LINQ爲對象 - 如果這是LINQ to SQL(或類似的東西),那麼您應該指定IQueryable<TaskRelation>Expression<Func<TaskRelation, string>>,以便過濾和投影可以在數據源完成。