1

Going nuts over this.

Simple query but its just not working. I simply need to get the company units that are not currently assigned to any users.

IDs are GUID type.

When debugging I see that there are 2 objects in companyUnits and 1 in userCompanyUnits. I'm trying to get that 1 companyUnit ( that doesn't exist in userCompanyunit) to show. Instead I get no results back.

Any idea what's wrong with the query? Maybe i can't compare based on guids ?

var companyUnitsList = from x in companyUnits
                       where !(from c in userCompanyUnits
                               select c.CompanyUnit.Id).Contains(x.Id)
                        select x;

Thanks in advance !

InspiredBy
  • 4,271
  • 6
  • 40
  • 67

3 Answers3

1

Here's a way of doing it without using the Except operator, and needing a custom IEqualityComparer:

        List<Tuple<int, string>> allUnits = new List<Tuple<int, string>>();
        allUnits.Add(new Tuple<int, string>(1, "unit1"));
        allUnits.Add(new Tuple<int, string>(2, "unit2"));
        allUnits.Add(new Tuple<int, string>(3, "unit3"));

        List<Tuple<int, string>> assignedUnits = new List<Tuple<int, string>>();
        assignedUnits.Add(new Tuple<int, string>(2, "unit2"));

        var unassigned = allUnits.Where(m => !assignedUnits.Any(asgn => asgn.Item1 == m.Item1));

//Yields unit1 and unit3
  • Item1 corresponds to Unit.ID
Kal_Torak
  • 2,532
  • 1
  • 21
  • 40
1

Since you have it tagged as sql, I'm assuming this is queryable's and running against the database. Depending on the ORM and whether you have navigation properties defined and usable, you could do:

var notAssigned =
    from x in companyUnits
    where x.Users.Any() == false
    select x;

IOW, whatever navigation property or collection exists to tie the company unit to the assigned user(s) is what you would use in the query (and would most likely translate to a sql 'exists')

James Manning
  • 13,429
  • 2
  • 40
  • 64
1
    var list1 = from s in new String[] {"ABC1","ABC2", "ABC3", "ABC4"} select new {Field1=s,Id = Guid.NewGuid().ToString()}  ;
    var list2 = new String[] {"ABC3","ABC4", "ABC5", "ABC6"} ;


    var requiredList = (from i1 in list1
                    from i2 in list2 
                    where !i1.Field1.Contains(i2)
                    select i1).Distinct();
Tilak
  • 30,108
  • 19
  • 83
  • 131