2013-05-01 263 views
0

因此,我们试图使用Linq语句显示信息,但我们遇到的问题是如果变量是“”,我们不希望创建一些元素 - 目前我们无法做到这一点,因为我们不能在linq语句中包含'if'语句。我们如何解决这个问题;我们的代码列在下面。在Linq语句中使用'if'语句

(延续 - 我们不想让“x.Phone”元素显示,如果将它设置为“”)

Root = new RootElement ("Student Guide") { 
     new Section("Contacts"){ 
      from x in AppDelegate.getControl.splitCategories("Contacts") 
      select (Element)new RootElement(x.Title) { 
       new Section(x.Title){ 
        (Element)new StyledStringElement("Contact Number",x.Phone) { 
         BackgroundColor=UIColor.FromRGB(71,165,209), 
         TextColor=UIColor.White, 
         DetailColor=UIColor.White, 
        }, 
       } 
      }, 
     }, 
    }; 

回答

3

您可以使用类似:

var root = new RootElement ("Student Guide") { 
    new Section("Contacts"){ 
     from x in AppDelegate.getControl.splitCategories("Contacts") 
     let hasPhone = x.Phone == null 
     select hasPhone 
     ? (Element)new RootElement(x.Title) { 
      new Section(x.Title){ 
       (Element)new StyledStringElement("Contact Number",x.Phone) { 
        BackgroundColor=UIColor.FromRGB(71,165,209), 
        TextColor=UIColor.White, 
        DetailColor=UIColor.White, 
       }, 
      } 
     } 
     : (Element)new RootElement(x.Title) 
    }, 
}; 

或者你可以打破你的Linq外出使用的方法 - 那么它就会少复制和粘贴代码 - 例如

var root = new RootElement ("Student Guide") { 
    new Section("Contacts"){ 
     from x in AppDelegate.getControl.splitCategories("Contacts") 
     select Generate(x) 
    }, 
}; 

private Element Generate(Thing x) 
{ 
    var root = new RootElement(x.Title); 
    var section = new Section(x.Title); 
    root.Add(section); 

    if (x.Phone != null) 
     section.Add(new StyledStringElement("Contact Number",x.Phone) { 
        BackgroundColor=UIColor.FromRGB(71,165,209), 
        TextColor=UIColor.White, 
        DetailColor=UIColor.White, 
       }); 

    return root; 
} 
0

潜在使用条件运算符?

string.IsNullOrEmpty(x.Phone) ? "Return Something if it is empty" : x.Phone; 

http://msdn.microsoft.com/en-us/library/ty67wk28(v=vs.80).aspx

+0

虽然,如果不是NullOrEmpty,我将如何使用它创建一个新的'StyledStringElement'?我自己尝试过,但还没有弄明白。 – 2013-05-01 08:49:31

+0

@LoadData为什么不传递一个空字符串?我不知道'StyledSTringElement'是什么:P – LukeHennerley 2013-05-01 09:20:18

+0

因为我们需要它作为StyledStringElement以我们想要的格式显示文本 - 我不知道我们能做到这点的其他原因。 – 2013-05-01 09:42:45

1

也许我失去了一些东西,但据我所知,你只是缺少一个where条款,不是吗?

var root = new RootElement ("Student Guide") { 
    new Section("Contacts"){ 
     from x in AppDelegate.getControl.splitCategories("Contacts") 
     where !string.IsNullOrEmpty(x.Phone) 
     select (Element)new RootElement(x.Title) { 
      new Section(x.Title){ 
       (Element)new StyledStringElement("Contact Number",x.Phone) { 
        BackgroundColor=UIColor.FromRGB(71,165,209), 
        TextColor=UIColor.White, 
        DetailColor=UIColor.White, 
       }, 
      } 
     }, 
    }, 
};