I have a list list with items in it like this
ElementA: Number=1, Version=1
ElementB: Number=1, Version=2
ElementC: Number=1, Version=3 <-
ElementD: Number=2, Version=1
ElementE: Number=2, Version=2 <-
ElementF: Number=3, Version=1 <-
and I want to select all items which have the highest Version in a group with items of same Number. (See the arrows above.)
I would like to use a query for this so I’ve tried this:
var result = from a in list where a.Version >=
(from b in list where b.Number == a.Number && b != a select b.Version).Max() select a;
This is working fine, if every group of items with the same Number consists of at least 2 elements, but otherwise it throws an InvalidOperationException if the inner query contains no elements.
How can I rewrite the query to get what I want? I would be grateful for every hint. 🙂
this should do the trick, but without copying your data myself I cannot test it:
as Henrik noticed this will only get you one item – I didn’t see the reason to get more because the items seemd only to consist of the two fields, but this is easily handeled – just add another group for the version:
This should result in a enumeration of Arrays with the largest versions – but again I cannot test so there might be syntax or semantic errors but the indent should be clear and errors easy to remove.