0

I am trying to get only the headers that have a details using this Lambda statement

list = list.Where(c=> c.CustomerSalesPeople.Count>0);

but i am getting a null exception when I try to return the results

return list.OrderBy(c => c.CustomerName).ToList();

I have stepped through the code and see the null exception is generated right after I executed the first statement. Is there a better way to accomplish this.

EDIT

I tried the suggestions and i was still getting a null value. I figured I would try to explain better. I need a Lambda expression that matches this Query

    SELECT *
  FROM [customer]
  where customer_record_id in (select distinct(customer_id)from customer_sales_person)
ChampChris
  • 1,565
  • 5
  • 26
  • 44

2 Answers2

1
list = list.Where(c=>c.CustomerSalesPeople.Count>0).SingleOrDefault();

if(list!=null)
  return list.OrderBy(c=>c.CustomerName).ToList();

return list;

or if you think, CustomerSalesPeople can be null then you can do this:

list = list.Where(c=>(c.CustomerSalesPeople==null) ||(c.CustomerSalesPeople.Count>0));

if(list!=null)
  return list.OrderBy(c=>c.CustomerName).ToList();

return list;

also you can look at .DefaultIfEmpty() extension.

Linq provides excellent extension methods to counter when empty result set is found. here they are:

  1. .FirstOrDefault()
  2. .DefaultIfEmpty()
  3. .SingleOrDefault()

UPDATE:

do this:

   List<int> uniqueIds= listOfCustomerSalesPerson.Select(s=>s.Id).ToList().Distinct();
   var requireListOfCustomers = GetAllCustomers().Where(s=>uniqueIds.Contains(s.id);

you can also embed these two separate calls in one though. but depending upon kind of data provider you are using, it might give you an error like,"use only primitive types".hence the separate list of ids.

for instance, if you are using EntityFramework 5.0 and SQL Server, you can do this.

myDbContext db= new myDbContext();
var requiredList = db.Customers.Where(s=>
                               (s.CustomerSalesPeople ==null)
                               ||
                               (s.CustomerSalesPeople.Select(o=>o.Id).Contains(s.Id))
                               ).ToList();

I've assumed, Customer contains List<CustomerSalesPeople> , it can be db.CustomerSalesPeople otherwise

Community
  • 1
  • 1
Manish Mishra
  • 12,163
  • 5
  • 35
  • 59
  • I changed the Select to Any and it worked perfectly. Dont think i was aware of passing the parent variable s to the subquery as a parameter. thanks – ChampChris Feb 25 '13 at 08:39
0

You can have null elements in your collection. Try to check nulls in where statement

return list != null ? 
   list.Where(c=> c!=null && c.CustomerSalesPeople.Count>0).
   OrderBy(c => c.CustomerName).ToList()
   :null;
Alex
  • 8,827
  • 3
  • 42
  • 58