3

I want to get an array of characters as string values in from strings in listOfStrings that have a sum smaller than 50, but I don't know how to do that with LINQ.

I have written the code below as an illustration of what I'm rying to do:

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;
                      }

Here listOfStrings is of type List<string[]>.

It would be hard to think of a more useless function; I'm just trying to find out how to execute stuff in lambda functions within LINQ, without making a new function to do it.

3
  • You seem to mixing up query syntax with method call syntax. Commented Jul 2, 2012 at 6:43
  • @tsukimi The function does not calculate the length, it calculates the sum of all characters Commented Jul 2, 2012 at 6:59
  • Do you want the integer value when you take s[i] or do you want the character value? Commented Jul 2, 2012 at 7:12

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

OK, I'll look that up, but what's the basic difference?
1

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" } }

Comments

0

Perhaps:

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

Comments

0

I think something like this might help you, I haven't compiled it so there might be some bugs 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());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.