Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check if the list with the same values exists

Tags:

c#

In these following code segment::

static void Main(string[] args)
{
   List<List<int>> bigList = new List<List<int>> { };
   bigList.Add(new List<int> { 1, 2 });
   bigList.Add(new List<int> { 2, 3 });
   bigList.Add(new List<int> { 3, 4 });
   List<int> subList = new List<int> { 1, 2 };    
   Console.WriteLine(bigList.Contains(subList));
}

the output is:: 'False'. then what is the method to check this. i mean how will the output become 'True'

like image 435
user2598365 Avatar asked Jul 19 '13 07:07

user2598365


4 Answers

If you don't care about duplicate entries in the lists you can use:

bigList.Any(b => new HashSet<int>(b).SetEquals(subList))

If you want both lists to contain exactly the same elements you can use this:

bigList.Any(b => b.OrderBy(x => x).SequenceEqual(subList.OrderBy(x => x)))

If you want both lists to have the same elements in the same order you can use this:

bigList.Any(x => x.SequenceEqual(subList))
like image 199
david.s Avatar answered Oct 01 '22 22:10

david.s


If the order doesn't matter you can use Any+All:

bool anyContains = bigList
    .Any(l => bigList.Count == l.Count && l.All(i => subList.Contains(i)));

Otherwise you can use Any + SequenceEqual

bool anySequencequals = bigList.Any(l => l.SequenceEqual(subList));
like image 28
Tim Schmelter Avatar answered Oct 01 '22 21:10

Tim Schmelter


Use the All linq statement

var result = bigList.Where(x => x.All(y => subList.Contains(y)));
like image 21
David Colwell Avatar answered Oct 01 '22 23:10

David Colwell


You can use SequenceEqual method to check with Any:

bigList.Any(x => x.SequenceEqual(subList))
like image 21
cuongle Avatar answered Oct 01 '22 21:10

cuongle