我有幾個函數,我知道正確工作。一個用正則表達式計算文本框中單詞的數量,另一個用正則表達式計算同一文本框中特定單詞(字符串)的實例。我確信這些都會返回預期的值。DataGrid問題 - 值總是顯示0?
但是,我顯然搞砸了函數來以某種方式填充我的datagrid,因爲keywordcount總是返回爲零,密度也是如此。
這裏是我的代碼:
public List<KeywordDensity> LoadCollectionData()
{
string thearticle = txtArticle.Text;
string[] keywordsarray = txtKeywords.Text.Split('\n');
bool isincluded = false;
int keywordcount = 0;
int thedensity = 0;
List<KeywordDensity> lsikeywords = new List<KeywordDensity>();
foreach (string s in keywordsarray)
{
if (s.Trim() != "")
{
keywordcount = KeywordCount(thearticle, s);
thedensity = keywordcount/WordCount(thearticle);
if (thearticle.Contains(s))
{
isincluded = true;
}
else
{
isincluded = false;
}
lsikeywords.Add(new KeywordDensity()
{
included = isincluded,
keyword = s,
occurences = keywordcount.ToString(),
density = thedensity.ToString()
});
}
}
return lsikeywords;
}
編輯@ 8:30 AM MST:想通了這個問題的一部分。使用「\ n」作爲分隔符不起作用。顯然,它只是將整個事件「分裂」成一個大塊,包括回車和提交。我將它改爲「\ r」,現在至少「Included」和「Occurences」部分工作正常。
現在唯一的問題是,「密度」不起作用。我意識到它不能被聲明爲int;但它仍然總是返回0 - 即使我將這個密度聲明爲float或var。
以下是否有問題?
thedensity = keywordcount/wordcount;
此外 - .ToString()函數截斷小數點加上所有的東西過去嗎?例如,如果一個變量的值是0.43,它只會轉換爲0?如果情況並非如此,我應該使用哪種變量類型?我會認爲浮動是適當的。
再次感謝!
EDIT @ 8:45 MST:太糟糕了,我不能接受多個答案。 '\ r'和var類型都是問題。我沒有意識到你不能通過除以兩個整數來計算浮點數。當我將源變量更改爲浮點以及密度變量時,它也起作用。
雙謝!
-Sootah
我假設數據類型被綁定爲DataGrid中的項目是KeywordDensity。既然你向我們保證KeywordCount正在正常工作,那麼你就沒有向我們展示`KeywordDensity`的代碼或者DataGrid的Xaml。 – AnthonyWJones 2011-01-14 12:23:44