I'm writing am application that I've previously posted questions on here, but I'm looking for similar advice if possible. I am looking for how best to write my code, as I have a working example, but to me it feels long winded.
The application first grabs 3 tables via DataContext:-
var contacts = db.GetTable<Contact>();
var distributionLists = db.GetTable<DistributionList>();
var JunctionTable = db.GetTable<ContactsDistribution>();
I then get the selected items from my listbox, which are distribution lists. A contact can be in more than one distribution list, so I first get the raw data from my database:
var listBoxItems = listBox1.SelectedItems.Cast<object>().Select(t => t.ToString());
var initialList = (from j in JunctionTable
where listBoxItems.Contains(j.DistributionName)
join c in contacts on j.ContactID equals c.ContactID
select new { c.ContactID,c.Surname,j.DistributionName, j.EmailFlag, j.SMSFlag}).ToList();
I then need to search the initialList
collection for users who require email notifications. I also need to remove duplicate entries, as a Contact can appear multiple times. So the list is made Distinct:-
var email = (from l in initialList
where l.EmailFlag.Equals(true)
select new { l.ContactID }).Distinct().ToList();
I then do the same search for Contacts that require SMS Notification from the selected lists:
var sms = (from l in initialList
where l.SMSFlag.Equals(true)
select new { l.ContactID }).Distinct().ToList();
Now that I have lists for both SMS & Email Notifications I need get the required email address or mobile number by doing this:
var smsMobileNumbers = (from s in sms
join c in contacts on s.ContactID equals c.ContactID
select new { c.MobileNumber }).ToList();
var emailAddresses = (from m in email
join c in contacts on m.ContactID equals c.ContactID
elect new { c.EmailAddress }).ToList();
Is there a cleaner way of writing this code or is there a better, more efficient way of achieving this?
1 Answer 1
The only change I would make would be to remove the two statements where you create the lists sms and email. They are redundant: by adding the EmailAddress and MobileNumber to the query where you are creating the initialList, you can do a select on the initialList.
var initialList = (from j in JunctionTable
where listBoxItems.Contains(j.DistributionName)
join c in contacts on j.ContactID equals c.ContactID
select new { c.ContactID, c.Surname, c.EmailAddress, c.MobileNumber,
j.DistributionName, j.EmailFlag, j.SMSFlag }).ToList();
I changed these more because I like this syntax better than the SQL like Linq.
var emailAddresses = initialList
.Where(l => l.EmailFlag)
.Select(l => l.EmailAddress).Distinct().ToList();
var smsMobileNumbers = initialList
.Where(l => l.SMSFlag)
.Select(l => l.MobileNumber).Distinct().ToList();