0

我可以使用更好的 LINQ 或 lambda 表达式来减少此 C# 代码中的循环吗?我本质上是在寻找一个 UNION 操作来删除重复项并标记两组中的项目。

public class LibraryLocation
{
    public string HoldingType { get; set; }
    public string LibraryLocationName { get; set; }
}

public class HoldingRepo
{
    public HoldingRepo(MyDbContext dbContext)
    {
    }

    public async Task<List<LibraryLocation>> FindLibraryLocationsByLibrary(int libraryId)
    {
        var result = new List<LibraryLocation>();

        var bookHoldings = (from bh in db.BookHoldings
                            where bh.LibraryId == libraryId
                            select bh).Select(x => x.LocationName).Distinct();

        var journalHoldings = (from jh in db.JournalHoldings
                               where jh.LibraryId == libraryId
                               select jh).Select(x => x.LocationName).Distinct();

        // TODO: Improve this by cleaning up three loops below?

        // Add common items
        foreach (var item in await bookHoldings.Intersect(journalHoldings).ToListAsync())
        {
            result.Add(new LibraryLocation { HoldingType = "BOTH", LibraryLocationName = item });
        }

        // Add book items
        foreach (var item in await bookHoldings.Except(journalHoldings).ToListAsync())
        {
            result.Add(new LibraryLocation { HoldingType = "BOOK", LibraryLocationName = item });
        }

        // Add journal items
        foreach (var item in await journalHoldings.Except(bookHoldings).ToListAsync())
        {
            result.Add(new LibraryLocation { HoldingType = "JOURNAL", LibraryLocationName = item });
        }

        return result;
    }
}
4

0 回答 0