英文:
Cast list to derived class
问题
Here is the translated code portion:
public class Auctions : List<Auction>
{
// Functions here
}
public class Auction
{
public string item_name { get; set; }
public long starting_bid { get; set; }
}
Auctions allAuctions; // With data
string distinctName; // With data
List<Auction> itemSet = allAuctions.Where(auction => auction.item_name.Contains(distinctName)).ToList();
The code portion has been translated into Chinese as requested.
英文:
public class Auctions : List<Auction>
{
// Functions here
}
public class Auction
{
public string item_name { get; set; }
public long starting_bid { get; set; }
}
Auctions allAuctions; // With data
string distinctName; // With data
List<Auction> itemSet = allAuctions.Where(auction => auction.item_name.Contains(distinctName)).ToList();
I'm trying to search through derived class
Auctions : List<Auction>
with a LINQ query. In the end, no matter what I try, I get either iterable object or base class (List<Auction>
).
How do I change my code to get result as derived class?
答案1
得分: 1
只需在 Auctions 类型上添加一个构造函数,该构造函数以 List<Auction> 为参数,并通过 AddRange()
方法添加。或者,您甚至可以重写 Auctions 类型上的 Explicit 和/或 Implicit 运算符,以便将 List<Auction> 强制转换为 Auctions 类型或将 List<Auction> 的实例分配给 Auctions 类型。
英文:
Just add a constructor on the Auctions type that takes a List<Auction> as an argument and adds it by AddRange()
method. or even you can override Explicit and/or Implicit operators on the Auctions type to be able to cast a List<Auction> to the Auctions type or assign instances of List<Auction> to the Auctions type.
public class Auctions : List<Auction>
{
public Auctions(){}
public Auctions(List<Auction> autions){
if(auctions == null)
throw new ArgumentNullException(nameof(auctions));
this.AddRange(auctions);
}
}
public static class AuctionsExtensions{
public static Auctions ToAuctions(this IEnumerable<Auction> auctions){
if(auctions == null) throw new ArgumentNullException(nameof(auctions));
return new Auctions(auctions.ToList());
}
}
// and then :
List<Auction> itemSet = allAuctions.Where(auction => auction.item_name.Contains(distinctName)).ToAuctions();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论