LuckWar15
LuckWar15

Reputation: 3

How can i check if there is in an item in one list that isn't in the other list?

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

Answers (4)

Pavel Anikhouski
Pavel Anikhouski

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

vendettamit
vendettamit

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

Chris Dunaway
Chris Dunaway

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

hawkstrider
hawkstrider

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

Related Questions