将数据加载到LINQ对象中以获取搜索结果类型方法的最有效方法

时间:2010-02-09 15:19:41

标签: c# linq .net-3.5 c#-3.0 subsonic

我目前有以下内容:

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

问题是我只需要返回实际拥有数据的一个属性以及Title属性,类似于。

 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 });
                    }
                }

2 个答案:

答案 0 :(得分:2)

如果两者包含标准怎么办?或者他们互相排斥?如果是的话

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

答案 1 :(得分:0)

我选择了3