gpt4 book ai didi

c# - LINQ 中两个列表的联合不起作用

转载 作者:行者123 更新时间:2023-11-30 23:29:19 25 4
gpt4 key购买 nike

我有一种方法可以显示数据库中存在的书籍以及借出的书籍。

当用户没有归还这本书时,这本书就变得不活动了。所以我写了一个 LINQ 查询,新用户可以在其中选择一本书。然后如果用户选择了一本丢失的书。他将被抛出一个该书不可用的消息。

这里我是用Union来查找活跃的图书和已借出未归还的图书。

但是重复的值在方法中返回。

public IEnumerable<UsageType> GetUsageType(int BookID = 0)
{
_db.Configuration.ProxyCreationEnabled = false;
List<UsageType> Uresult = new List<UsageType>();
List<UsageType> result = new List<UsageType>();
try
{
if (BookID == 0)
{
result = (from Usage in _db.USAGE_TYPE
where Usage.IS_ACTIVE == true
select new
{
UsageTypeId = Usage.USAGE_TYPE_ID,
UsageTypeName = Usage.USAGE_TYPE_NAME,
IsActive = Usage.IS_ACTIVE
}).AsEnumerable()
.Select(x => new UsageType
{
UsageTypeId = x.UsageTypeId,
UsageTypeName = x.UsageTypeName,
IsActive = x.IsActive.HasValue ? x.IsActive.Value : false
}).Distinct().ToList();
}
else
{
result = (from Usage in _db.USAGE_TYPE
where Usage.IS_ACTIVE == true
select new
{
UsageTypeId = Usage.USAGE_TYPE_ID,
UsageTypeName = Usage.USAGE_TYPE_NAME,
IsActive = Usage.IS_ACTIVE
}).AsEnumerable()
.Select(x => new UsageType
{
UsageTypeId = x.UsageTypeId,
UsageTypeName = x.UsageTypeName,
IsActive = x.IsActive.HasValue ? x.IsActive.Value : false
}).ToList();

var savedUsagetype = (from Usage in _db.USAGE_TYPE
join usageCategory in _db.USAGE_CATEGORY on Usage.USAGE_TYPE_ID equals usageCategory.USAGE_TYPE_ID
join book_usage in _db.BOOK_USAGE
on usageCategory.USAGE_CATEGORY_ID equals book_usage.USAGE_CATEGORY_ID
where book_usage.Book_ID == BookID
select new
{
UsageTypeId = Usage.USAGE_TYPE_ID,
UsageTypeName = Usage.USAGE_TYPE_NAME,
IsActive = Usage.IS_ACTIVE
}).AsEnumerable()
.Select(x => new UsageType
{
UsageTypeId = x.UsageTypeId,
UsageTypeName = x.UsageTypeName,
IsActive = x.IsActive.HasValue ? x.IsActive.Value : false
}).ToList();



Uresult= result.Union(savedUsagetype).Distinct().ToList();
}

return Uresult;
}
catch (Exception ex)
{
return null;
}
}

最佳答案

你正在比较你自己类的对象,所以你应该实现 IEquatable在你的UsageType类告诉 linq 如何比较你的对象。例如:

public class UsageType : IEquatable<UsageType>
{
public int UsageTypeId {get; set;}
...

public bool Equals(UsageType other)
{
return this.UsageTypeId == other.UsageTypeId;
}
public override bool Equals(object other)
{
return this.UsageTypeId == ((UsageType)other).UsageTypeId;
}
public override int GetHashCode()
{
return this.UsageTypeId.GetHashCode();
}
}

现在您可以使用 UsageType获取 IEqualityComparer<UsageType> 的实例:

Uresult = result.Union(savedUsageType,IEqualityComparer<UsageType>.Default).ToList();

注意:始终覆盖 object.Equalsobject.GetHashcode()也。如果不这样做,旧代码仍然使用非泛型 Enumerable会给出意想不到的结果,因为它们使用其他逻辑进行比较,超出您的预期。

关于c# - LINQ 中两个列表的联合不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35548031/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com