1

I have two lists that is

List<int> comments ;
List<int> no_checks;

Now i would like to see if all no_checks have comments. So during my processing of data whenever a comment is added am adding its id to comment list and when a no radio is selected am adding its id to no_checks

So a sample output to console has

1.

 below should return false;
 comment=[12, 13,15]
 no_checks = [12,13,15,17 ] //one no has no comment

2

 below should return true  
 comment=[12, 13,15]
 no_checks = [12,13 ] //all have comments  

So am stuck here

public bool allnoHaveComments(){
 var allhave=true;

 for(var i=0; i<no_checks.count; i++){ 
    //if one no_checks is not contained in comments allhave=false

  }
  return allhave;
 }

How can i proceed to compare and check to see that id's in no_checks are all contained in comments else if they are not return false

How can i go about this

  • Does order matter? If not, then you might consider using `HashSet` instead of `List`. A hashset represents a set of unordered things, and directly supports operations like the one you want. – Eric Lippert Jul 24 '17 at 18:01

3 Answers3

3
bool isallnoHaveComments= !no_checks.Except(comment).Any();
Sajeetharan
  • 203,447
  • 57
  • 330
  • 376
1

This gives you the values in no_checks that aren't in comments

no_checks.Except(comments)

Your problem is basically Check whether an array is a subset of another.

Nathan Cooper
  • 5,904
  • 4
  • 35
  • 71
-1

I have used here two for loops, one for comments list and the other for no_checks which is nested inside loop for comments

private bool check_Commentexist(List<int> comments, List<int> no_checks)
{
    var j = 0;
    var k = 0;

    Boolean commentexist = false;
    for (var i = 0; i < no_checks.Count; i++)
    {
        j = no_checks[i];
        commentexist = false;
        for (var x = 0; x < comments.Count; x++)
        {
            k = comments[x];
            if (j == k) { commentexist = true; break; }
        }
        //if no match found for atleast on element break the loop
        if (commentexist == false) break;
        //else if match found the looping continues to check the
        //next element in 'no_checks' for a mathcing comment
    }

    return commentexist;
}
vrksoln
  • 27
  • 3
  • The LINQ approach is asymptotically faster (`O(n + m)` instead of `O(n * m)`), easier to read, shorter, and simpler. The only reason to consider this approach is if you're on .Net 2.0. However, even in that case I would recommend avoiding the nested loop in favor of a single loop with a contains check (both for readability and as a precursor to copying one of the lists into a hash). – Brian Jul 25 '17 at 13:57