I have the following lists of list.
List<List<int>> paths = new List<List<int>>();
paths.Add(new List<int>() { 0,1 });
paths.Add(new List<int>() { 0, 2 });
paths.Add(new List<int>() { 0, 4 });
paths.Add(new List<int>() { 1, 2 });
paths.Add(new List<int>() { 0, 3 });
and I have another List of int like this
List<int> ends = new List<int>(){3,4};
Now I need to filter records where any number in the inner list in paths contains any numbers from the ends list, which for this example would be the following records.
{0,3}
{0,4}
I tried something like this
paths.Where(x => x.Where(y => ends.Contains(y))).ToList();
CodePudding user response:
paths.Where(x => x.Any(z => ends.Contains(z)))
CodePudding user response:
Use Any
to solve your problem:
var res = paths.Where(list => list.Any(item => ends.Any(end => end==item))).ToList();
or shorter
var res = paths.Where(list => list.Any(item => ends.Contains(item))).ToList();
Result:
CodePudding user response:
LINQ syntax would be an expressive alternative for this:
var matches = (from p in paths
from e in ends
where p.Contains(e)
select p).Distinct();
CodePudding user response:
class Program
{
private static void Main(string[] args)
{
var paths = new List<List<int>>
{
new List<int>() { 0, 1 },
new List<int>() { 0, 2 },
new List<int>() { 0, 4 },
new List<int>() { 1, 2 },
new List<int>() { 0, 3 }
};
var ends = new List<int>(){3,4};
var results = paths.Where(x => ends.Any(x.Contains));
// display results
foreach(var result in results)
Console.WriteLine(JsonSerializer.Serialize(result));
}
}
//[0,4]
//[0,3]