Bertrand Paul Bertrand Paul - 1 month ago 10
C# Question

Improving a linq query if possible

I'm trying to fetch a list of items that have the following characteristics. I need to highlight the ones that only differ by the field "item_differ". I have therefore written the following code to find the desired records. This code does work for what I'm looking for but was wondering if there are smarter ways(both fewer lines and better performing or any)

void Main()
var MyItemList = GetItemList();

var Pair_of_items = (from p in MyItemList
let true_items = from f in MyItemList
where (new { p.item1, p.item2, p.item3,
p.item4, p.item5}
== new { f.item1, f.item2, f.item3,
f.item4, f.item5})
&& f.item6_differ != p.item6_differ
select f
select true_items).SelectMany(x => x);

// Define other methods and classes here

public class MyClass
public string item1 { get; set; }
public string item2 { get; set; }
public string item3 { get; set; }

public string item4 { get; set; }
public string item5 { get; set; }
public bool item6_differ { get; set; }

Any comment will be highly appreciated.


I think this returns the same result but much more efficient:

var Pair_off_items = 
    from p in MyItemList
    join f in MyItemList 
    on new {p.item1, p.item2, p.item3, p.item4, p.item5} equals new {f.item1, f.item2, f.item3, f.item4, f.item5}
    where f.item6_differ != p.item6_differ
    select f;