này nên làm điều đó. Tôi đã không xây dựng một thử nghiệm cho nó cụ thể.
var nextProducts = from item1 in recommendations.Select((rec, idx) => new { Rec = rec, Index = idx })
join item2 in recommendations.Select((rec, idx) => new { Rec = rec, Index = idx })
on item1.Index equals item2.Index - 1
where item1.Rec.Products.Any(p => p.Code == "A")
&& item1.Rec.Products.Any(p => p.Code == "B")
select item2.Rec;
Nếu bạn cần cả hai hồ sơ, báo cáo kết quả lựa chọn có thể là
select new { MatchingItem = item1.Rec, NextItem = item2.Rec };
Nhưng sau đó bạn sẽ phải làm một nhóm để giải thích cho một mục phù hợp là mục cuối cùng trong danh sách (có sẽ không phải là một mục tiếp theo trong trường hợp đó).
var nextProducts = from item1 in recommendations.Select((rec, idx) => new { Rec = rec, Index = idx })
join item2 in recommendations.Select((rec, idx) => new { Rec = rec, Index = idx })
on item1.Index equals item2.Index - 1
into groupjoin
from i2 in groupjoin.DefaultIfEmpty()
where item1.Rec.Products.Any(p => p.Code == "A")
&& item1.Rec.Products.Any(p => p.Code == "B")
select new { MatchingItem = item1.Rec, NextItem = i2 == null ? null : i2.Rec };
Mã I đã làm kiểm tra tương tự với danh sách chuỗi.
List<string> list = new List<string>() { "a", "b", "c", "a", "d", "a", "e" };
var query = from item1 in list.Select((s, idx) => new { Item = s, Index = idx })
join item2 in list.Select((s, idx) => new { Item = s, Index = idx })
on item1.Index equals item2.Index - 1
where item1.Item == "a"
select item2.Item;
Trả về b, d và e.
+1 Để sử dụng cú pháp lambda. –