Refracted Paladin
Refracted Paladin

Reputation: 12216

Check if List<string> contains any value besides specified

I need to check if a List contains any values outside of 3 specified.

Example: I have this var sourceList = new List<string>("A", "B", "C", "D", "E"); and I want to check that list contains any value BESIDES "E", "F", "G". Just a Bool is fine and sourceList is a dynamic subset of a predefined list that the User would have selected. My BESIDES List would be static.

Thanks,

Upvotes: 1

Views: 1318

Answers (7)

Dong
Dong

Reputation: 61

var sourceList = new List<string>{"A", "B", "C", "D", "E"};
var besidesList = new List<string>{"E", "F", "G"};  
var anyBesides = sourceList.Any(t => !besidesList.Contains(t));

Upvotes: 0

Dustin Kingen
Dustin Kingen

Reputation: 21245

It is less desirable to create a new list with Except and the current Any solution cannot be reused for different combinations of letters.

A combination of Contains and Any should suffice.

var sourceList = new List<string> { "A", "B", "C", "D", "E" };
var except = new[] { "E", "F", "G" };

var containsExcept = sourceList.Any(x => except.Contains(x));

Upvotes: 1

Alyafey
Alyafey

Reputation: 1453

var sourceList = new List<string>{"A", "B", "C", "D", "E"};

 bool res =sourceList.SequenceEqual(new string[] { "A", "B", "C"});

Also don't forget there is no constructor such you have written:

var sourceList = new List<string>("A", "B", "C", "D", "E");

It should be:

var sourceList = new List<string>{"A", "B", "C", "D", "E"};

Upvotes: 0

George Johnston
George Johnston

Reputation: 32258

User Except and Any extensions to accomplish your goal:

var sourceList = new List<string>{"A", "B", "C", "D", "E"};
var c = sourceList.Except( new List<string>{ "E", "F", "G"}).Any();

Upvotes: 3

Douglas
Douglas

Reputation: 54877

var sourceList = new List<string>("A", "B", "C", "D", "E");
var checkList = new List<string>("E", "F", "G");
bool anyBesides = sourceList.Except(checkList).Any();

Upvotes: 2

Jon G
Jon G

Reputation: 4164

var flag = sourceList.Except(new[] { "E", "F", "G" }).Any();

Upvotes: 7

Andrei
Andrei

Reputation: 56688

Using LINQ:

bool contains = sourceList.Any(t => (t != "E" && t != "F" && t != "G"));

Upvotes: 5

Related Questions