LINQ过滤 - 优化

时间:2014-04-22 19:42:43

标签: c# linq

我进行一次数据库访问以获取实体列表。 然后,我想将此列表分为2个列表,一个用于未过期的实体(使用开始和结束),我称之为TopListings,另一个是常规列表,已过期或开始/结束日期为null (不是TopListings的那些)

我不完全确定哪个过滤器被禁用以分成2个列表,我应该先获得首选列表,然后根据第二个列表中的NOT列表来过滤第二个列表吗?

var listings = ListingAdapter.GetMapListings(criteria);

var topListings = listings.Where(x => x.TopStartDate >= DateTime.Now && x.TopExpireDate >= DateTime.Now);

//I AM NOT SURE WHAT THIS LINE SHOULD BE
var regularListings = listings.Where(x => x.TopStartDate < DateTime.Now || x.TopExpireDate < DateTime.Now || x.TopStartDate == null || x.TopExpireDate == null );

谢谢

4 个答案:

答案 0 :(得分:3)

您可能想要使用LookUp

像这样:

var lookup = listings.ToLookup(x => x.TopStartDate >= DateTime.Now && x.TopExpireDate >= DateTime.Now);
var topListings = lookup[true];
var regularListings = lookup[false]; // I assume everything not a topListing is a regular listing.

如果这还不够,你可以创建一个枚举

enum ListingType { Top, Regular, WhatEver };

...

var lookup = listings.ToLookUp(determineListingType); // pass a methoddelegate that determines the listingtype for an element.

...

var topListings = lookup[ListingType.Top];
var regularListings = lookup[ListingType.Regular];
var whateverListings = lookup[ListingType.WhatEver];

答案 1 :(得分:2)

在这种情况下,使用循环可能更容易,而不是Linq运算符:

var topListings = new List<Listing>();
var regularListings = new List<Listing>();
foreach (var x in listings)
{
    if (x.TopStartDate >= DateTime.Now && x.TopExpireDate >= DateTime.Now)
        topListings.Add(x);
    else
        regularListings.Add(x);
}

这也更有效,因为列表只列举一次。

答案 2 :(得分:1)

看一下&#39;除了&#39;操作员使事情变得容易一些。您可能必须首先在topListings上添加.ToList()。

var regularListings = listings.Except(topListings);

http://blogs.msdn.com/b/charlie/archive/2008/07/12/the-linq-set-operators.aspx

答案 3 :(得分:1)

使用直接前进的常规foreach循环。您可以一次性遍历listing并将项目添加到适当的集合中。如果您是LINQ类型的人,ForEach扩展名是您正在寻找的:

var topListings = new List<Listing>();
var regularListings = new List<Listing>();

listing.ForEach(item=>{
                      if (x.TopStartDate < DateTime.Now 
                            ||       // I've inverted the condition, since it is faster-one or two conditions will be checked, instead of always two
                          x.TopExpireDate < DateTime.Now)
                        regularListings.Add(x);
                      else
                        topListings.Add(x);
                });