Wesley
Wesley

Reputation: 5621

Second Linq filter for multiple conditions

I have a class (simplified) as follows:

class AppMeta
{
    public int Id { get; set; }
    public string Scope { get; set; }
    public User CreatedBy { get; set; }
}

I've created a LINQ statement that properly filters results by cross referencing a list of integers, and discarding matches:

var hiddenApps = List<int>();
//populate hiddenApps
var listItems = List<rawdata>;
//populate listItems
List<AppMeta> apps = AppMeta.Collection(listItems).Where(i => !hiddenApps.Contains(i.Id)).ToList()

My question is, I need to further filter this list as follows,

(Where Scope == "user" && Where User.LoginName == CurrentUser.LoginName)

Can I still do that in one Linq statement, I.E. Can I combine that with my line above? What's the best way to do this?

Upvotes: 0

Views: 11190

Answers (2)

roybalderama
roybalderama

Reputation: 1640

Instead of creating another query, why don't you try adding those conditions to your Where method?

var loginName = CurrentUser.LoginName;
List<AppMeta> apps = AppMeta.Collection(listItems)
                        .Where(i => !hiddenApps.Contains(i.Id) && 
                                    i.Scope == "user" &&
                                    i.CreatedBy == loginName )
                        .ToList();

Just make sure that CurrentUser.LoginName type is User

Upvotes: 0

Habib
Habib

Reputation: 223187

You can specify multiple conditions in your Where clause. Modify your Where clause as:

.Where(i => !hiddenApps.Contains(i.Id) 
            && i.Scope == "user" 
            && i.CreatedBy.LoginName == CurrentUser.LoginName )

So your query would be:

List<AppMeta> apps = AppMeta.Collection(listItems)
                            .Where(i => !hiddenApps.Contains(i.Id) 
                                   && i.Scope == "user" 
                                   && i.CreatedBy.LoginName == CurrentUser.LoginName)
                            .ToList();

Upvotes: 7

Related Questions