-1

I'm a beginner with LINQ.

How can I convert this to a LINQ statement?

List<Foo> myList = new List<Foo>();
myList.AddRange(// here I add my items);

foreach (Foo x in myList)
{
    if (x.IsRequired() == false) throw new Exception();
}

to a LINQ statement? Like:

myList.ForEach(x => //something here);

I tried the following but that didn't work for me.

myList.ForEach(x => if (x.IsRequired() == false) throw new Exception());
Laur Ivan
  • 4,117
  • 3
  • 38
  • 62
Happy Bird
  • 1,012
  • 2
  • 11
  • 29
  • [ForEach](https://msdn.microsoft.com/en-us/library/bwabdf9z(v=vs.110).aspx) is not a _LINQ_ statement, it's a method of `List` collection. – Rahul Singh Feb 23 '17 at 09:54
  • 1
    Possible duplicate of [How do I convert Foreach statement into linq expression?](http://stackoverflow.com/questions/24193898/how-do-i-convert-foreach-statement-into-linq-expression) – Saurabh Srivastava Feb 23 '17 at 09:55
  • What type does `IsRequired()` return? – Nkosi Feb 23 '17 at 10:03

4 Answers4

5

I'd say

if (MyList.Any(x => x.IsRequired() == false))
{
    throw new Exception();
}

IsRequired() It's a method that returns a Boolean

so you can also shorten

if (MyList.Any(x => !x.IsRequired()))
{
    throw new Exception();
}
fubo
  • 44,811
  • 17
  • 103
  • 137
1

The answer that fubo gave is good if you just want to see if any of the elements in your list is not required. If you want to get the actual element(s), you can do it like this:

First Element

Foo notRequired = MyList.FirstOrDefault(x => !x.IsRequired());
if ( notRequired != null)
{
    // Do something with `notRequired`
}

All Elements

IEnumerable<Foo> notRequired = MyList.Where(x => !x.IsRequired());
if (notRequired.Count() > 0)
{
    foreach (var v in notRequired)
    {
        // Do something with `v`
    }
}
Abion47
  • 22,211
  • 4
  • 65
  • 88
1

Officially ForEach is not a LINQ statement. It usually only works for Lists.

From your code I assume that you want to throw an exception if any of the Foo objects in MyList has a false IsRequiredvalue.

You statement would be:

if (MyList.Any(foo => !foo.IsRequired))
    throw new Exception();

In words: if any of the foo elements in MyList has a false IsRequired value, throw a new Exception

The nice thing from using Any instead of first creating a list before checking, is that if you have an IEnumerable, and one of the first elements in the list would throw an exception, the rest of your list would not have been created in vain. See StackOverflow: What are the benefits of deferred execution?

Later you wrote:

The problem is that I want to find all Foo elements in myList which are not required. It's seems not possible with the Any method, it will fail on the first one.

If you want to find all Foo elements in the list that are not required, you still can use Linq, using Enumerable.Where:

var notRequiredFoos = myList
    .Where(elementInList => !elementInList.IsRequired);

usage:

foreach (var notRequiredFoo in notRequiredFoos)
{
    Console.WriteLine($"Foo element {notRequiredFoo.ToString} is not required");
}

Or if you want to throw an exception as soon as you found one, Linq will still help you: Enumerable.FirstOrDefault

var notRequiredFoo= myList
    .Where(elementInList => !elementInList.IsRequired);
    .FirstOrDefault();
if (notRequiredFoo != null)
{   // we found a Foo that is not required
    throw new MyException(notRequiredFoo);
}
// else: all Foos are required

Again, you still don't have to check all elements in the list, it will stop as soon as one is found.

Community
  • 1
  • 1
Harald Coppoolse
  • 28,834
  • 7
  • 67
  • 116
  • Thanks, nice answer, very descriptive. The problem is that I want to find all Foo elements in myList which are not required. It's seems not possible with the Any method, it will fail on the first one. – Happy Bird Feb 23 '17 at 10:24
  • @HappyBird I posted an answer, where you can get all elements which are not required. It can be fitted into the if-statement. Have a look – Mong Zhu Feb 23 '17 at 12:05
1

After reading your comments and the additional information :

The problem is that I want to find all Foo elements in myList which are not required. It's seems not possible with the Any method, it will fail on the first one.

Assuming Foo has some information that you would like to pass to your exception like a string Information you could get all of them assign them to a new list and check then for Any(). and do all that in the If-Clause:

List<Foo> temp = new List<Foo>();

if ((temp = MyList.Where(x=>!x.IsRequired()).ToList()).Any())
{
    // now pass the information of them all into the exception
    throw new Exception(String.Join("\t", temp.Select(y=>y.Information)));
}
Mong Zhu
  • 23,309
  • 10
  • 44
  • 76