4

我有这个查询

List<int> AuctionIds = 
   (from a in _auctionContext.Auctions
    where a.AuctionEventId == auction.AuctionEventId
    select new { a.Id }).ToList();

但我收到一个编译错误

Cannot implicitly convert type 'System.Collections.Generic.List<AnonymousType#1>' to 'System.Collections.Generic.List<int>'

AuctionIds 应该是什么类型?

编辑

AuctionIds 字段实际上在另一个类(模型类)中,所以我不能只使用 var。我不敢相信 Jon Skeet 没有回答这个问题。

4

2 回答 2

0

您正在将匿名对象添加到List<int>.. 如果您要按照自己的方式进行操作.. 我会使用var关键字..

var AuctionIds = 
       (from a in _auctionContext.Auctions
        where a.AuctionEventId == auction.AuctionEventId
        select new{Id = a.Id}).ToList();

原因是我不知道匿名对象是什么类型。但编译器应该能够处理它。

编辑:

呃,关于创建一个AuctionIDModel类?

 public class AuctionIDModel
    {
       int Id{get;set;}
    }

    List<AuctionIDModel> AuctionIds = 
           (from a in _auctionContext.Auctions
            where a.AuctionEventId == auction.AuctionEventId
            select new AuctionIDModel{Id = a.Id}).ToList();
于 2012-11-06T12:44:14.780 回答
0

你可以这样做:

List<int> AuctionIds = _auctionContext.Auctions
    .Where(a => a.AuctionEventId == auction.AuctionEventId)
    .Select(a => a.Id)
    .ToList();
于 2012-11-06T13:20:48.280 回答