Reputation: 3
List<string> equipment = new List<string>();
equipment.Add("Football");
equipment.Add("Golf Ball");
equipment.Add("Baseball");
List<string> myEquipment = new List<string>();
myEquipment.Add("Football");
myEquipment.Add("Golf Ball");
myEquipment.Add("Basketball");
If i have the above, how would i check if there is an item in myEquipment that isn't in equipment?
Upvotes: 0
Views: 111
Reputation: 23238
The simplest solution is to use Except
method
var diff = myEquipment.Except(equipment);
Another solution is to use HashSet
and ExceptWith
. It has almost the same complexity with previous solution (both O(n)
), but HashSet
will skip the duplicated values
var set = new HashSet<string>(equipment);
var mySet = new HashSet<string>(myEquipment);
mySet.ExceptWith(set);
Contains
method also work, but has some performance overhead
var item = equipment.FirstOrDefault(e => !myEquipment.Contains(e));
You'll get the first item, which isn't present in a second list, or null
value
Upvotes: 1
Reputation: 14677
Here's two way look up to get items that don't exist in other from both lists:
var b = equipment.Concat(myEquipment).ToLookup(x => x)
.Select(x => new { x.Key, Count = x.Count()})\
.Where(x => x.Count == 1);
Upvotes: 0
Reputation: 11216
You can use the Linq Except
method:
void Main()
{
List<string> equipment = new List<string>();
equipment.Add("Football");
equipment.Add("Golf Ball");
equipment.Add("Baseball");
List<string> myEquipment = new List<string>();
myEquipment.Add("Football");
myEquipment.Add("Golf Ball");
myEquipment.Add("Basketball");
var missingEquipment = myEquipment.Except(equipment);
}
Upvotes: 0
Reputation: 4341
You can use Linq to do this pretty easily
myEquipment.Any(c => !equipment.Contains(c));
If you need the items you could do
var notInEquipment = myEquipment.Where(c => !equipment.Contains(c));
Upvotes: 2