2010-02-09 40 views
1

目前,我有以下幾點:將數據加載到LINQ對象的搜索結果類型的方法最有效的方法

public IEnumerable<News> NewsItems 
     { 
      get { return from s in News.All() where s.Description.Contains(SearchCriteria) || s.Summary.Contains(SearchCriteria) select s; } 
     } 

問題是,我只需要返回,實際上有數據的一個屬性,以及在標題屬性,類似於。

return from s in News.All() where s.Description.Contains(SearchCriteria) || s.Summary.Contains(SearchCriteria) select new {Title = s.Title, Data = //Description or Summary containing the data 

如何確定哪個包含搜索查詢?

更新:我有這個,但它顯然擊中DB 3次

var FoundInSummary = News.All().Any(x => x.Summary.Contains(SearchCriteria)); 

       var FoundInDesc = News.All().Any(x => x.Description.Contains(SearchCriteria)); 

       IEnumerable<NewsEventSearchResults> result = null; 

       if ((FoundInSummary && FoundInDesc) || (FoundInSummary)) 
       { 
        result = (from s in News.All() where s.Summary.Contains(SearchCriteria) select new NewsEventSearchResults { Title = s.Title, Data = s.Summary, ID = s.ID }).AsEnumerable(); 
       } 
       else if (FoundInDesc) 
       { 
        result = (from s in News.All() where s.Description.Contains(SearchCriteria) select new NewsEventSearchResults { Title = s.Title, Data = s.Description, ID = s.ID }).AsEnumerable(); 
       } 

       return result; 

更新2:這是比較有效?

var ss = (from s in News.All() where s.Description.Contains(SearchCriteria) || s.Summary.Contains(SearchCriteria) select s).ToList(); 
       List<NewsEventSearchResults> resultList = new List<NewsEventSearchResults>(); 
       foreach (var item in ss) 
       { 
        bool FoundInSummary = item.Summary.Contains(SearchCriteria); 
        bool FoundInDesc = item.Description.Contains(SearchCriteria); 
        if ((FoundInSummary && FoundInDesc) || (FoundInSummary)) 
        { 
         resultList.Add(new NewsEventSearchResults { Title = item.Title, Data = item.Summary, ID = item.ID }); 
        } 
        else if (FoundInDesc) 
        { 
         resultList.Add(new NewsEventSearchResults { Title = item.Title, Data = item.Description, ID = item.ID }); 
        } 
       } 

回答

0

我去選項3

2

如果他們包含哪些標準?或者它們是互斥的?如果是這樣

Data = (s.Description != null ? s.Description : s.Summary) 
+0

好點!如果它們都包含它,我將返回摘要 – Jon 2010-02-09 15:30:11

相關問題