how to fetch data from Func using generic list and linq

280 views Asked by At

I am new to C#.

I have a class account with name and balance. I made a list of those accounts, and now what I'm trying to do is to somehow get all users whose balance is greater than 20000 using Func.

I am aware of that my code ma be wrong, so please, help me out.

class entry
{       
    public static void Main(string[] args)
    {
        List<account> list1 = new List<account>()
        {
            new savingAcc("a",50000),
            new currentAcc("b",30000),
            new savingAcc("c",80000),
            new currentAcc("d",10000),
            new savingAcc("e",7000),
            new savingAcc("f",85000)     

        };          

        Func<List<account>,List<account>> myhand = mySorting.mysal;
        /* here something which will print my data as foreach is not working */
    }
}

public class mySorting
{
    public static List<account> mysal(List<account> lis)
    {
        return (from i in lis where i._Balance > 50000 select i).ToList();
    }
}
1

There are 1 answers

1
user35443 On BEST ANSWER

You could do something like this, without using Func<>

foreach(account in mySorting.mysal(list1)) {
    /* do your stuff on an account */
}

Or better

foreach(account in (from i in lis where i._Balance > 50000 select i)) {
    /* do your stuff on an account */
}

Or even better

(from i in lis where i._Balance > 50000 select i).ForEach(a => a.DoStuff());

Edit:

With Func<> you could use

Func<List<account>, List<account>> myhand = mySorting.mysal;
foreach(account in myhand(list1)) {
    /* do your stuff on an account */
}

or

Func<List<account>, List<account>> myhand = mySorting.mysal;
myhand(list1).ForEach(a => a.DoStuff());