Robin
Robin

Reputation: 2723

How to blend an if-else into linq query syntax statement

I have two collections. A collection of Notifications and a collection of Document types. I need to collect information about the both of them and add an extra field depending on something as well. However, I don't have a clue how to do this.

I get the document type ID and name from the Document types collection. And I get only a document type ID from the Notifications collection. If an ID is there in both, there should be an extra field added to the return that is a string value of simply "Subscribed". If not, the string value should be "Unsubscribed". I could work with a bool value as well of course.

This is what I got so far.

Code to get what I need from the notifications:

var notifications = from n in repository.Get<Domain.Notification>()
                                where n.UserId == userID
                                select n.DocTypeId;

Code to get what I need from the document types:

(Note: if I can do the join right here, I would prefer that.)

var doctypes =  from d in repository.Get<Domain.DocumentType>()
                where d.SupplierID == SuppId
                select new { d.Id, d.Name};

What I don't have yet is the join. I don't know how I can add a field to the select new, as it keeps giving me errors when I do. And I don't know how I can do a sort of if-else statement in the Query syntax. I know I once did that in TSQL, so I was hoping it is possible in linq as well.

Code that I have tried but 'feels' wrong to me:

string temp = "unsubscribed";
            bool temp2 = true;
            var testing =
                from d in repository.Get<Domain.DocumentType>()
                where d.SupplierID == SuppId
                select new { d.Id, d.Name, temp, temp2 = false };

So here I tried some things out to get a third field added. It feels somewhat dirty to me as how I did it, but if there is no alternative I'll use this. What I need now is how I can add the if-else part. I know how to do a multiplefrom select, but just not how to do the if-else part.

EDIT

What is inside the two collections:

Document types:

Notification:

What I would like as an output:

A list that has three items per object, namely:

Upvotes: 0

Views: 48

Answers (1)

jitender
jitender

Reputation: 10429

             var notifications = from n in repository.Get<Domain.Notification>()
                            where n.UserId == userID
                            select n.DocTypeId;

             var docTypes = repository.Get<Domain.DocumentType>().Where(d =>d.SupplierID == SuppId).Select(d =>new {
             d.Id,
             d.Name,
             hasEntryInNotifications=notifications.Any(n => n ==d.Id)
             })

Upvotes: 1

Related Questions