-1

我写了一个 LINQ 查询子句,但是出现了一个错误。任何人都可以帮助我。在此先感谢:

list = (from cr in dt.AsEnumerable()
select new Cards
{
   MemberNumber = cr.Field<string>("MemberNumber"),
   if( cr.Field<int>("CardState")==0)
   {
          CardState ="aaa";
   }
   if( cr.Field<int>("CardState")==1)
   {
     CardState ="bbb";
   }
   if( cr.Field<int>("CardState")==2)
   {
      CardState ="ccc";
   }
  if( cr.Field<int>("CardState")==3)
  {
     CardState ="ddd";
  }
  if( cr.Field<int>("CardState")==4)
  {
    CardState ="eee";
   }
  }).ToList<Cards>();
4

1 回答 1

3

您不能在初始化程序中拥有这样的分支逻辑。但是,您可以将其编写为一系列三元运算符:

list = (from cr in dt.AsEnumerable()
select new Cards
{
   MemberNumber = cr.Field<string>("MemberNumber"),
   CardState = ( cr.Field<int>("CardState")==0) ? "aaa" : 
               ( cr.Field<int>("CardState")==1) ? "bbb" :
               ( cr.Field<int>("CardState")==2) ? "ccc" :
               ( cr.Field<int>("CardState")==3) ? "ddd" :
               ( cr.Field<int>("CardState")==4) ? "eee" :
               ( cr.Field<int>("CardState")==5) ? "bbb" : null
}).ToList<Cards>();

尽管更好的解决方案可能是将该代码块分离到一个单独的函数中并从您的初始化程序中调用它:

list = (from cr in dt.AsEnumerable()
select new Cards
{
   MemberNumber = cr.Field<string>("MemberNumber"),
   CardState = GetCardState( cr.Field<int>("CardState"))
  }).ToList<Cards>();
于 2012-11-06T01:51:57.750 回答