各位大大好!小弟,最近剛學asp.net core mvc,買了一本<ASP.NET Core 7 MVC 範例實戰演練>,作者:奚江華,我目前做ch02範例!
我遇到一些問題,想請教各位大大!
問題1:請教LINQ查詢這段,這是甚麼語法呢?最基本語法是甚麼呢?
//以LINQ查詢泛集合
var friendsQuery = from f in friends where f.Country == "USA" || f.Country == "Korea" select f;
問題2:下面程式碼,我的VisualStidio 2022的Models/Frinde.cs的Name和Country出現波浪底線要 請問string後面加?嗎?,為甚麼要加[?]呢
public class Friend
{
/*
Models/Friends.cs為了Controllers/CSharpBasisController的IActionResult
的函式內建立Friend物件和List集合
*/
public string Name { get; set; }
public string Country { get; set; }
}
問題3:
下面程式碼是正常List宣告物件語法
List<Friend> friends = new List<Friend>
{
new Friend { Name = "Rose",Country = "USA"},
new Friend { Name = "David", Country = "Japan" },
new Friend { Name = "John", Country = "USA" },
new Friend { Name = "Bob", Country = "Italy" },
new Friend { Name = "Johnson", Country = "Thailand" },
new Friend { Name = "Cindy", Country = "Japan" },
new Friend { Name = "Lucy", Country = "Korea" },
new Friend { Name = "Angel", Country = "Italy" },
new Friend { Name = "Maya", Country = "Thailand" },
new Friend { Name = "Max", Country = "Korea" }
};
但Visual Studio2022在上面程式碼..提示,然後我照提示,為甚麼要改成下面程式碼呢?
//集合式初始化設定式(新寫法)
List<Friend> friends = new()
{
new Friend { Name = "Rose",Country = "USA"},
new Friend { Name = "David", Country = "Japan" },
new Friend { Name = "John", Country = "USA" },
new Friend { Name = "Bob", Country = "Italy" },
new Friend { Name = "Johnson", Country = "Thailand" },
new Friend { Name = "Cindy", Country = "Japan" },
new Friend { Name = "Lucy", Country = "Korea" },
new Friend { Name = "Angel", Country = "Italy" },
new Friend { Name = "Maya", Country = "Thailand" },
new Friend { Name = "Max", Country = "Korea" }
};
不好意思!造成各位大大誤會!我昨天有實作出書中範例,版型畫面被我改掉!我是做完後,有不懂語法才請教各位大大,我就附上自己練習成果,照片如下!下次我在it邦幫這裡發問問題會附上練習成果!請大家多多包涵和諒解!
LinQ SQL
var friendsQuery = from f in friends where f.Country == "USA" || f.Country == "Korea" select f;
跟MSSQL對照~
select f.* from friends as f where f.Country = 'USA' or f.Country = 'Korea'
var friendsQuery = friends.Where(f => f.Country == "USA" || f.Country == "Korea");
直接學 Lambda 表示式 會比較好搞懂
還有你應該要先買一本 C# 的書先把基本語法搞懂才對