AStupidNoob
AStupidNoob

Reputation: 2050

Linq with anonymous methods

I'm just getting started with LINQ, and I'm having some troubles.

Say I wanted to do something like this:

IEnumerable<String[]> = from s in listOfStrings
                      where () => {
                          int sum = 0;
                          for (int i=0; i<s.Length(); i++)
                          {
                              sum += s[i];
                          }
                          return sum < 50;
                      }
                      select () =>
                      {
                          String[] t = new String[s.Length()];
                          for (int i=0; i<s.Length(); i++)
                          {
                              t[i] = s[i].toString();
                          }
                          return t;
                      }

Basically I want to get an array of characters as string values in from strings in listOfStrings that have a sum smaller than 50.

This is just an example though, It would be hard to think of a more useless function huh, I'm just trying to find out how to execute stuff in lambda functions within linq, without making a new function to do it.

Thanks!

Upvotes: 3

Views: 9166

Answers (4)

Tomas Jansson
Tomas Jansson

Reputation: 23472

I think something like this might help you, I haven't compiled it so it might be some bug in the code but the concepts are there:

var result = listOfStrings.Where(y => y.Split().Aggregate(0, (y, x) => int.Parse(y)) < 50).Select(y => y.Split());

Upvotes: 1

McGarnagle
McGarnagle

Reputation: 102773

Using lambda functions is probably easier in this case...

var listOfStrings = new List<string>() { "foo", "bar" };
IEnumerable<string[]> result = 

    // restrict to strings where the sum of ASCII values is < 1000
    listOfStrings.Where(item => item.Sum(ch => (int)ch) < 1000)

    // select each as an array of strings
    .Select(item => item.Select(ch => ch.ToString()).ToArray());

// result:  { { "f", "o", "o" }, { "b", "a", "r" } }

Upvotes: 1

Jocke
Jocke

Reputation: 2284

Perhaps:

listOfString.Where(s => s.Length < 50).ToArray();

Upvotes: -1

s.m.
s.m.

Reputation: 8043

If you use the method-chaining syntax instead of the query syntax (i.e. listOfStrings.Where(...)), you can stick the lambda in there.

Upvotes: 2

Related Questions