Home

Logical Conjunction and Disjunction

     

Conjunction

You can use a logical conjunction to combine two or more Boolean expressions. To do this, use the where statement to create the expression as you see fit. Here is an expression that uses a logical disjunction (&&) operation:

private void Exercise_Load(object sender, EventArgs e)
{
   var numbers = new List<int>();

   numbers.Add(12);
   numbers.Add(45);
   numbers.Add(38);
   numbers.Add(5);
   numbers.Add(128);
   numbers.Add(525);
   numbers.Add(2448);
   numbers.Add(39);
   numbers.Add(632);
   numbers.Add(207);

    var number = from n
                 in numbers
                 where n % 2 == 0 && n <= 100
                 select n;

    foreach (var member in number)
        lbxNumbers.Items.Add(member.ToString());
}

This would produce:

Numbers

Once again, remember that the use of parentheses makes it easier to read the code and better understand it:

private void Exercise_Load(object sender, EventArgs e)
{
    var numbers = new List<int>();

   numbers.Add(12);
   numbers.Add(45);
   numbers.Add(38);
   numbers.Add(5);
   numbers.Add(128);
   numbers.Add(525);
   numbers.Add(2448);
   numbers.Add(39);
   numbers.Add(632);
   numbers.Add(207);

    var number = from n
                 in numbers
                 where (n % 2 == 0) && (n <= 100)
                 select n;

    foreach (var member in number)
        lbxNumbers.Items.Add(member.ToString());
}

Or better yet:

private void Exercise_Load(object sender, EventArgs e)
{
    var numbers = new List<int>();

   numbers.Add(12);
   numbers.Add(45);
   numbers.Add(38);
   numbers.Add(5);
   numbers.Add(128);
   numbers.Add(525);
   numbers.Add(2448);
   numbers.Add(39);
   numbers.Add(632);
   numbers.Add(207);

    var number = from n
                 in numbers
                 where ((n % 2) == 0) && (n <= 100)
                 select n;

    foreach (var member in number)
        lbxNumbers.Items.Add(member.ToString());
}

To negate a conjunction, precede it with a ! operator. Remember that a conjunction is made of two parts. Therefore, if you want to negate only the first part, precede it with !. If you want to negate the whole conjunction, put the conjunction in parentheses but precede it with ! (outside the parentheses).

Disjunction

When creating a LINQ statement, you can use a logical disjunction. You do this with the C#'s OR operator, which is ||.

 
 

Previous Copyright © 2010-2016, FunctionX Next