简体   繁体   中英

Linq PredicateBuilder With Complex AND & OR

Using PredicateBuilder and make a predicate on many ID from a table , we have result of many list with filterd ID like this:

在此处输入图片说明

predicate builder make a predicate with OR for {aaa,bbb,ccc,ddd} . i want to have first item of each group. is it possible with linq query ?

 var predicate = PredicateBuilder.False<someobject>();
        foreach (var item in items)
        {
            predicate = predicate.Or(p => p.id == item.id );
        }

...

Unless this is part of a bigger query requiring predicate builder, this simple LINQ should work:

var result = items.GroupBy(x => x.Id)
                  .Select(x => x.First());

Or if you want to order the elements first, then choose the first from each group:

var result = items.OrderBy(x => x.Id)
                  .ThenBy(x => x.Quantity)  // not sure what 2nd column is called
                  .GroupBy(x => x.Id)
                  .Select(x => x.First());

If you want to build a predicate based on you rule (to get a first item from a group), you need to build a predicate based on this rule:

Example class:

public class Person
{
    public int Id { get; set; }      //example: "aaa"
    public string Name { get; set; }    //example: 1
}

Query:

var predicate2 = PredicateBuilder.False<Person>();

foreach (var item in items.GroupBy(x => x.Name).SelectMany(x => x.OrderBy(y => y.Id).Take(1)))
{
    predicate2 = predicate2.Or(p => p.Id == item.Id);
}

var fnc2 = predicate2.Compile();
var filtered2 = allItems.Where(fnc2).ToList();

As a result it will build a predicate like this (for data you have provided):

p => p.Id == 1 || p.Id == 10 || p.Id == 15 || p.Id == 17

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM