【发布时间】:2022-01-03 17:17:33
【问题描述】:
我有以下对象:
public class Store : BaseEntity
{
public virtual List<ConsumerClubDto>? RelatedConsumerClubs { get; set; }
public virtual List<GiftDto>? RelatedGifts { get; set; }
}
这两个列表从同一个接口实现。
我在每个列表上运行以下扩展方法。 此时我已经复制了这个方法——一个在 ConsumerClubDto 上运行,另一个是 GiftDto。
public static async Task UpdateList(this List<ConsumerClubDto>? clubsDto, Store storeFromRepo, AppDbContext dbContext)
{
if (clubsDto?.Count > 0)
{
foreach (ConsumerClubDto clubDto in clubsDto)
{
if ((storeFromRepo.RelatedConsumerClubs?.FindIndex(x => x.Id == clubDto.Id) == -1))
{
ConsumerClub t = await dbContext.ConsumerClubs.FindAsync(clubDto.Id);
storeFromRepo.RelatedConsumerClubs.Add(t);
}
}
List<ConsumerClub> clubsToRemove = new List<ConsumerClub>();
foreach (ConsumerClub club in storeFromRepo.RelatedConsumerClubs)
{
if (clubsDto.FindIndex(x => x.Id == club.Id) == -1)
clubsToRemove.Add(club);
}
if (clubsToRemove.Count > 0)
{
foreach (ConsumerClub club in clubsToRemove)
storeFromRepo.RelatedConsumerClubs.Remove(club);
}
}
}
我确信我可以编写一个通用方法并避免重复代码。我不确定如何。
欢迎指点。
【问题讨论】:
-
public static async Task UpdateList(this List<ICommonInterfaceName>? clubsDto, Store storeFromRepo, AppDbContext dbContext)有效吗? (将ICommonInterfaceName替换为你提到的通用接口名称)