2013-02-13 77 views
1

我想寫一個發現是長於4個字符,並打印出來的所有用戶名對我的數據庫查詢,我的代碼有云:查詢安慰

也 我需要去改變它到列表/數組的某種返回類型?

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; 

    } 

我怎麼可以將每個名稱添加到數組中?

回答

2

使用Length屬性來檢查字符串長度。 試試這個:

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

您可以在短短的一行代碼(使用LINQ)做到這一點:

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

寫入到控制檯並返回它們作爲一個列表。您也可以將字符長度作爲參數傳遞給函數。

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