减少集合操作中的循环?

时间:2017-03-03 22:14:09

标签: c# linq lambda set-operations

我可以减少这个C#代码的循环,也许使用更好的LINQ或lambda表达式?我实际上是在寻找一个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;
    }
}

0 个答案:

没有答案