将列表转换为派生类

huangapple go评论75阅读模式
英文:

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&lt;Auction&gt;
{ 
    // 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&lt;Auction&gt; itemSet = allAuctions.Where(auction =&gt; auction.item_name.Contains(distinctName)).ToList();

I'm trying to search through derived class

Auctions : List&lt;Auction&gt;

with a LINQ query. In the end, no matter what I try, I get either iterable object or base class (List&lt;Auction&gt;).

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&lt;Auction&gt;
{ 
    public Auctions(){}
    public Auctions(List&lt;Auction&gt; autions){
         if(auctions == null)
              throw new ArgumentNullException(nameof(auctions));
         this.AddRange(auctions);
    }
}

public static class AuctionsExtensions{
    public static Auctions ToAuctions(this IEnumerable&lt;Auction&gt; auctions){
        if(auctions == null) throw new ArgumentNullException(nameof(auctions));
        return new Auctions(auctions.ToList());
    }
}

// and then :
List&lt;Auction&gt; itemSet = allAuctions.Where(auction =&gt; auction.item_name.Contains(distinctName)).ToAuctions();

huangapple
  • 本文由 发表于 2023年5月21日 01:12:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76296445.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定