darko
darko

Reputation: 793

query on db print to console

i want to write a query on my db that finds all the user name that are longer then 4 char and print them , my code goes:

also do i need to change it to some kind of return type for list/array?

public string[] FindNameByLength(int minimumCharNumber)
    {

        var query = from u in db.Users
                    where u.FullName.Length > minimumCharNumber
                    select u.FullName;


        string[] namesLength;
        int counter;

        foreach (var s in query)
        {
         namesLength.Concat(new[] {s });
        }
        return namesLength;

    }

how could i add each name into an array?

Upvotes: 1

Views: 569

Answers (3)

Kaf
Kaf

Reputation: 33829

Write to console and return them as a List. Also you could pass the character length as a parameter to the function.

public List<string> FindName(int ChrLength)
{
       var query = db.Users.Where(u => u.FullName.Length > ChrLength)
                           .Select(u => u.FullName).ToList();

       foreach(var s in query) 
           Console.WriteLine(s);
       return query;
}

Upvotes: 1

gzaxx
gzaxx

Reputation: 17600

You can do this in just one line of code (with LINQ):

public void FindName()
{
    db.Users.Where(x => x.FullName.Length > 4).ToList().ForEach(x => Console.WriteLine(x.FullName));
}

Upvotes: 1

Iswanto San
Iswanto San

Reputation: 18569

Use Length property to check string length. Try this :

 public void FindName()
   {
       var query = from u in db.Users
                   where u.FullName.Length > 4
                   select u.FullName;

       foreach(var s in query) 
           Console.WriteLine(s);
   }

Upvotes: 2

Related Questions