user677607
user677607

Reputation:

need help converting C# foreach loop to lambda

Can the following loop be implemented using IQueryable, IEnumerable or lambda expressions with linq

private bool functionName(int r, int c)
{
    foreach (S s in sList)
    {
        if (s.L.R == r && s.L.C == c)
        {
            return true;
        }
    }

    return false;
}

if so how?

Upvotes: 5

Views: 1513

Answers (4)

bastianwegge
bastianwegge

Reputation: 2498

since you should provide more information about the classes (s.L.R ??) you use and I don't know what you really want as outcome of the function, this is not 100 percent sure:

return sList.Any(s => s.L.R == r && s.L.C == c);

/e: seems like I was a bit to late, sorry guys. Was not copiying yours.

Upvotes: 0

tchrikch
tchrikch

Reputation: 2468

One example

private bool functionName(int r,int c)
{
  var ret = from s in sList where s.L.R==r&&s.L.C==c select s;
  return ret.Count()>0;
}

Upvotes: -1

Jackson Pope
Jackson Pope

Reputation: 14640

Try:

private bool functionName(int r, int c)
{
    return sList.Any(s => s.L.R == r && s.L.C == c);
}

The Any extension method in Linq applies to an IEnumerable sequence (which could be a List for example) and returns true if any of the items in the sequence return true for the given predicate (in this case a Lambda function s => s.L.R == r && s.L.C == c).

Upvotes: 6

Paul
Paul

Reputation: 5576

something like:

return sList.Any(s => s.L.R == r && s.L.C == c);

Upvotes: 6

Related Questions