I need to implement something,
I have an item list with different priorities and I need to select the items based on these priorities. For that, I have another list of priorities. If priority "one" does not match it should check the second priority and so on. This can be checked with a simple foreach loop and check with .Any() function. But I'm wondering this can be done with a single LINQ query.
enum Brand
{
Nike,
Adidas,
Levis
}
class Info
{
public Brand Brand { get; set; }
public int Status{ get; set; }
public int Group{ get; set; }
}
var list = new Info[]
{
new Info{Brand = Brand.Nike, Status = 0, Group = "C"},
new Info{Brand = Brand.Adidas, Status = 0, Group = "D"},
new Info{Brand = Brand.Nike, Status = 4, Group = "A"},
new Info{Brand = Brand.Levis, Status = 0, Group = "B"},
new Info{Brand = Brand.Adidas, Status = 5, Group = "B"}
};
List<string> groupPririties = new List<string>() { "B", "D", "A", "E" };
According to this item list and priority list, I should get Levis and Addidas only. But if those two are not on the list it should return Adidas item and so on. If I dont have any priority matching items in my list, it should return null.
Can I acheive this with linq query only?
But I'm wondering this can be done with a single LINQ query
var priorityItems = list
.GroupBy(x => x.Group)
.Where(grp => groupPririties.Contains(grp.Key))
.OrderBy(grp => groupPririties.IndexOf(grp.Key))
.FirstOrDefault();
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.