将过滤和字符串连接与DRY相结合

时间:2014-10-08 11:02:39

标签: linq c#-4.0 refactoring

考虑以下代码:

var marketing = marketingRepository.Suggestions(selectedID, sourceTypeID, providerID);

SomeObject sObj = new SomeObject();

SomeObject.StudentIds = string.Join(",", marketing.Where(p => p.TypeID == 43)
                 .Select(p => p.MappingID.ToString()));

supplierMarketingObject.TeacherIds = string.Join(",", marketing.Where(p => p.TypeID == 44)
                .Select(p => p.MappingID.ToString()));

supplierMarketingObject.OtherIds = string.Join(",", marketing.Where(p => p.TypeID == 45)
               .Select(p => p.MappingID.ToString()));

根据TypeId过滤营销列表并将其分配给相应的集合。 由于有很多重复的代码,有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

您可以使用常用操作定义本地lambda:

Func<int, string> getMappingIdsByTypeId =
    typeId => string.Join(",", marketing.Where(p => p.TypeID == typeId)
                                        .Select(p => p.MappingID.ToString()));

sObj.StudentIds = getMappingIdsByTypeId(43);
supplierMarketingObject.TeacherIds = getMappingIdsByTypeId(44);
supplierMarketingObject.OtherIds = getMappingIdsByTypeId(45);