1
votes

Im really new to LINQ so I'm trying to figure out how to execute method with lambda expressions.

   public void GetData()
    {

     using (MyClassesDataContext context = new MyClassesDataContext())
                {
                    var problems = (from p in context.Problems select p).Take(10);
                    problems.Select(t => DisplayData(t.Text));
                }

    }

     public void DisplayData(string Text)
            { 

            }

I'm getting this error:

The type arguments for method 'System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

at this line:

 problems.Select(t => DisplayData(t.Text));

What am I doing wrong?

3
DisplayData is void. It should return something. Or something like problem.ToList().ForEach(t => DisplayData(t.Text))L.B
Problems is SQL Table that I just draged from Server explorer and created to MyClassesDataContext(I'm not sure what do you mean by definition)formatc
Thanks, problem.ToList().ForEach(t => DisplayData(t.Text)) will do!formatc

3 Answers

4
votes

Select operator is used to create a projection - i.e. the lambda expression passed as an argument instructs how to create new object out of each object in the collection.

What you want to do is, instead, to perform an action on each item from the collection. Use foreach loop for that:

var problems = (from p in context.Problems select p).Take(10);

foreach (var t in problems)
{
     DisplayData(t.Text);
}
0
votes

I think that if you make the following change to your code, it will work fine:

problems.Select(t => { DisplayData(t.Text); return true; })
-1
votes

Parallel.ForEach. Here is a sample example...

Reference - Executes a foreach operation in which iterations may run in parallel.


Sample Class

class abc
{
    public int i;
}

Sample LINQ Code

List<abc> d = new List<abc>();
d.Add(new abc { i = 1 });
d.Add(new abc() { i = 2 });
d.Add(new abc() { i = 3 });
d.Add(new abc() { i = 4 });

var problems = (from p in d select p).Take(2);
int k = 0;
System.Threading.Tasks.Parallel.ForEach(problems, j =>
    {
        abcd(ref j.i);
        k += j.i;
    }
);

Sample Function

void abcd(ref int i)
{
    i++;
}