Jyina
Jyina

Reputation: 2902

What is the equivalent Linq Where code to IF condition in Vb.Net?

I have the below code with a plain If condition and <> operator. I am looking if there is an equivalent Linq code to If condition? If so, which Linq operator is appropriate in this scenario? Thank you!

Dim member as System.Reflection.MemberInfo

If member.Name <> "Person" And member.Name <> "Balance" And member.Name <> "Links" Then
    lstItems.Add(member.Name)
End If

Upvotes: 0

Views: 117

Answers (3)

Eldar Dordzhiev
Eldar Dordzhiev

Reputation: 5135

Assuming items is an original collection

lstItems = items.Where(Function(member) member.Name <> "Person" And member.Name <> "Balance" And member.Name <> "Links").ToList()

Actual solution is

lstItems = { member }.Where(Function(item) item.Name <> "Person" And item.Name <> "Balance" And item.Name <> "Links").ToList()

Upvotes: 3

Daniel Mann
Daniel Mann

Reputation: 59016

The idiomatic way to do this in VB would be to use query syntax instead of method chaining.

E.g.

lstItems = From member In members
                Where member.Name <> "Person" _
                And member.Name <> "Balance" _
                And member.Name <> "Links" _
                Select member

The other answers are also correct, but they're using method chaining. Method chaining is quite ugly in VB (IMHO).

Upvotes: 1

Damir Arh
Damir Arh

Reputation: 17855

You should use Where:

lstItems = members
    .Where(m => m.Name <> "Person" && m.Name <> "Balance" && m.Name <> "Links")
    .Select(m => m.Name)
    .ToList();

I assumed members is the original collection you want to filter.

I used C# syntax because I'm more familiar with it. You should be able to convert it to VB.

Upvotes: 1

Related Questions