【问题标题】:Creating a List<T> that matches items first, then adding in the rest using LINQ创建一个 List<T> 首先匹配项,然后使用 LINQ 添加其余项
【发布时间】:2017-08-18 01:29:36
【问题描述】:

这应该很容易。

我遇到了一个 LINQ 问题,希望有人能帮助我。假设我有这个课程:

public class Product
{
    public int ProductID {get; set;}        // Primary key
    public int CategoryID {get; set; }      // Foreign key
}

那么假设我需要找到List&lt;Products&gt;.Where(p =&gt; p.CategoryID == 2)中的所有产品,然后列出其余的产品。

换句话说,我需要先列出与 CategoryID 匹配的任何产品,然后列出其余不匹配的产品。

有什么建议吗?

【问题讨论】:

  • 尝试以下操作:ListSelect(p => order = p.CategoryID == 2? 1 : 2).OrderBy(x => x.order)
  • 您需要什么格式的结果?又是一个列表?

标签: c# linq


【解决方案1】:

你可以使用Except方法:

var categoryTwoItems = products.Where(p => p.CategoryID == 2);
var otherItems = products.Except(categoryTwoItems);

如果您想按类别 ID 对所有商品进行排序,但要先使用带有 CategoryId == 2 的商品,您可以执行以下操作:

var catId2First = products
    .OrderByDescending(p => p.CategoryID == 2)
    .ThenBy(p => p.CategoryID)
    .ToList();

【讨论】:

    【解决方案2】:

    您可以使用 except,并使用 2 个查询。

    var categoryProducts = products.Where (p => p.CategoryId == 2).ToArray();
    var others = products.Except(categoryProducts);
    

    或者您也可以一次性使用 groupBy。

       var productGroup= product.GroupBy(p => p.CategoryId == 2);
       var category2Products = productGroups.First(p => p.Any(x=> x.CategoryId==2));
       var others = productGroups.Except(category2Products); 
    

    【讨论】:

      【解决方案3】:

      你也可以使用ToLookup:

      ILookup<bool, Product> categorizedProducts = products.ToLookup(p => (p.CategoryId == 2));
      
      IEnumerable<Product> category2Products = categorizedProducts[true];
      IEnumerable<Product> nonCategory2Products = categorizedProducts[false];
      

      【讨论】:

        【解决方案4】:

        你可以通过排序来做到这一点:

        List<Products>.OrderByDescending(p => p.CategoryID == 2);
        

        【讨论】:

          猜你喜欢
          • 2011-12-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-06-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-03-05
          相关资源
          最近更新 更多