2012-04-07 52 views
2

我正在使用from..select linq查詢從XML文件讀取數據,數據非常龐大。我能讀的最大的一組數據是1100行,每行包含100個字符。這會導致我的手機掛起並導致應用程序崩潰。在模擬器上,它工作正常,但需要大量的時間來加載。如何根據條件使用FROM..SELECT選擇Linq元素?

現在我想要的是基於一些我希望在查詢中包含數據元素的條件。作爲一個例子,我現在擁有的是...

var dataSet = from r in something.Elements("chapter") 
       select new dictChapter{ 
        Name = r.Attribute("Name").Value, 
        Desc1 = r.Attribute("Description1").Value, 
        Desc2 = r.Attribute("Description2").Value, 
        Desc3 = r.Attribute("Description3").Value 
       }; 
ListBox.DataContext = dataSet; 

但我想根據設置選擇說明。我想是這樣(我知道這是行不通的,但我想解釋一下我想要做的)

var dataSet = from r in something.Elements("chapter") 
       select new dictChapter{ 
        Name = r.Attribute("Name").Value, 
        if (ShowDesc1 == true) 
         Desc1 = r.Attribute("Description1").Value, 

        if (ShowDesc2 == true) 
         Desc2 = r.Attribute("Description2").Value, 

        if (ShowDesc3 == true) 
         Desc3 = r.Attribute("Description3").Value 
       }; 
ListBox.DataContext = dataSet; 
  1. 我如何用C夏普實現這一目標?
  2. 有沒有更好的解決方案來解決我的問題?

非常感謝

回答

2

使用conditional operator "?:"

var dataSet = from r in something.Elements("chapter") 
       select new dictChapter{ 
        Name = r.Attribute("Name").Value, 
        Desc1 = ShowDesc1 ? r.Attribute("Description1").Value : String.Empty, 
        Desc2 = ShowDesc2 ? r.Attribute("Description2").Value : String.Empty, 
        Desc3 = ShowDesc3 ? r.Attribute("Description3").Value : String.Empty, 

       }; 
+0

謝謝它部分回答我的問題,因爲我知道如何應用條件。邏輯不起作用。我仍然有同樣的問題。 – wafers 2012-04-07 13:19:41

2

你可以嘗試這樣的:

var dataSet = from r in something.Elements("chapter") 
       select new dictChapter{ 
        Name = r.Attribute("Name").Value, 
        Desc1 = (ShowDesc1 ? r.Attribute("Description1").Value : null), 
        Desc2 = (ShowDesc2 ? r.Attribute("Description2").Value : null), 
        Desc3 = (ShowDesc3 ? r.Attribute("Description3").Value : null), 
       }; 

這是不是你想要什麼,因爲所有Desc1-3性質總是在每個元素上設置,但如果ShowDesc1-3爲false,則它們設置爲null。

+0

感謝您的回答。你是對的!它並沒有幫助我解決問題。不知道下一步該做什麼! :) – wafers 2012-04-07 13:21:40