Linq返回指定类型

1.

public IEnumerable<RiskInfo> GetRisksByUsername()
{
AuroraDataContext db = new AuroraDataContext();
var list = db.GetRisksByUsername().Select(c => new RiskInfo { Number = c.Number, Name = c.Name });

return list;
}

 

public class RiskInfo
{
public int? Number { get; set; }
public string Name { get; set; }
}

 

2.

下面给出个简单的例子:

 

public interface IStockStatistics
{
IT_Modelnumber ModelNumber {
get ; set ; }
int TotalAmount { get ; set ;}
}

 

public class StockStatistics:IStockStatistics 

    {

        private int _id;

        private IT_Modelnumber  _model;

        private int _amount;



        public int Id

        {

            get{return _id  ;}

            set{_id =value ;}

        }

        public IT_Modelnumber ModelNumber

        {

            get { return _model; }

            set { _model = value; }

        }

        public int TotalAmount

        { 

            get { return _amount; }

            set { _amount = value; }

        }

    }

 

public ICollection<IStockStatistics > GetStatistics()

         {

              var result = from p in Database.StockDS

                           group p by p.ToModelnumber into g

                           select new StockStatistics

                           {

                               Id = g.Key.Id,

                               ModelNumber = g.Key,

                               TotalAmount = g.Sum(p => p.Amount)

                          };

             return result.AsEnumerable().Cast<IStockStatistics>().ToList().AsReadOnly();

         }

 

 简单的说这个方法就是将原本匿名的类型转换成我们已知的类型,但这个类型不存在,所以需要我们先进行定义。

select new StockStatistics :new 后面的类型有些资料中省略了,但我在自己的环境中省略后编译没有通过。

 
 

你可能感兴趣的:(LINQ)