I am trying to fetch elements having a common id from 2 sets of arrays but that id must be unique to each array, the array can contain multiple-element with the same id, in that case, it should not fetch the item. Only if the id is common between two arrays and is unique to each array.
var fetchElement = ArrayA.Where(x=>ArrayB.Any(y=>y.Id == x.Id)).ToArray();
Above code will return me the elements with common ID. eg:
Array 1
[
{id = 123, name ="abc"},{id=456, name="def"},{id=123, name ="ghi"}
]
Array 2
[
{id =123, name ="abc"},{id=456, name ="def"}
]
Array 1 and Array 2 both have id 123 and 456 but I only want the element with id 456 as it is unique for both of the arrays.
CodePudding user response:
Here's a simple approach:
var Array1 = new[] { (id: 123, name: "abc"), (id: 456, name: "def"), (id: 123, name: "ghi") };
var Array2 = new[] { (id: 123, name: "abc"), (id: 456, name: "def") };
var query = from a1 in Array1.Where(x => Array1.Count(y => y.id == x.id) == 1)
join a2 in Array2.Where(x => Array2.Count(y => y.id == x.id) == 1)
on a1.id equals a2.id
select (a1, a2);
foreach (var x in query)
{
Console.WriteLine($"{x.a1} {x.a2}");
}
For sure there are more efficient, but maybe it's sufficient for you. Demo
