1

I want to Exact Matching List of object based on list of int
I have two list, first
List<int> list1 = new List<int>(){5,6};-- assume these are university Ids
second I have list of objects like
List<UniversityGroup> list2 = new List<UniversityGroup>();
new UniversityGroup ({UniversityGroupId = 1 ,UniversityId = 5 });objects matched o/p should'1'
new UniversityGroup ({UniversityGroupId = 1 ,UniversityId = 6 });
---------------------------------------------------------------------------------------------
new UniversityGroup ({UniversityGroupId = 2 ,UniversityId = 5 });--ignored as it contains just '5'
---------------------------------------------------------------------------------------------
new UniversityGroup ({UniversityGroupId = 3 ,UniversityId = 2 });--ignored elements are not matching
new UniversityGroup ({UniversityGroupId = 3 ,UniversityId = 3 });

And wanted output as universityGroupId Where ids from list1 will match with UniversityId from list2 ,

Expected Output:=> [1] or
new UniversityGroup ({UniversityGroupId = 1 ,UniversityId = 5 });
new UniversityGroup ({UniversityGroupId = 1 ,UniversityId = 6 });

I have tried using foreach but ,I dont think its an optimized solution, so looking for shorthand or optimized linq query .

XORG_99
  • 180
  • 4
  • 15
  • *I have tried using foreach but ,I dont think its an optimized solution, so looking for ... linq query* - what do you think LINQ uses internally? :) – Caius Jard Feb 08 '20 at 08:35
  • linq internally uses foreach i know, but i had written un-optimized code using some couple of foreach loops. – XORG_99 Feb 08 '20 at 08:40

1 Answers1

0

if I get your problem statement right, you might be able to leverage of SequenceEqual in your query:

    var list1 = new List<int> { 5, 6 };
    var list2 = new List<UniversityGroup> {
        new UniversityGroup{ UniversityGroupId = 1 ,UniversityId = 6 },
        new UniversityGroup{ UniversityGroupId = 1, UniversityId = 5 },
        new UniversityGroup{ UniversityGroupId = 2, UniversityId = 5 },
        new UniversityGroup{ UniversityGroupId = 3, UniversityId = 2 },
        new UniversityGroup{ UniversityGroupId = 3, UniversityId = 3 }
    };
    list1.Sort(); // depending on your input data you might want to apply some ordering so you could match sequences 6,5 to 5,6
    var result = list2.GroupBy(g => g.UniversityGroupId)
                    .Where(g => g.Select(i => i.UniversityId)
                                .OrderBy(x => x) // this might be optional if you can guarantee source sequence order
                                .SequenceEqual(list1)) // here's the thing
                    //.Select(g => g.Key) // if you want just UniversityGroupId
                 ;

It is however hard to say whether this query is going to be any better than your couple of foreach loops without seing those.

timur
  • 14,239
  • 2
  • 11
  • 32