我如何使用泛型类通过linq编写有用的代码?

时间:2010-08-11 13:18:31

标签: c# visual-studio linq generics

我想使用泛型类来缩短我的代码,因为

1)GetMaintData(int taskID)RelTypeId和RefMaintenance
2)GetAliSpReqs(int taskID)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 个答案:

答案 0 :(得分: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>>,以便过滤和投影可以在数据来源。