LINQ in C#
consoleGuy
1 min read
selalunya kita akan guna loop dan condition with loop untuk process data yang dari mana2. contohnya dari List. tapi cara ni leceh dia jadi panjang kat foreach loop tu. sebenarnya aku rasa tak best heheh.
List<string> BookList = new List<string>()
{
"Sejarah Pak Maun",
"Alice in WonderLand",
"Penyamun hoi hoi ya hoi",
"ABC",
"Buku 555",
"0"
};
foreach(string x in BookList)
{
if(x.Length > 6)
{
Console.WriteLine("mak kau hijau");
}
}
so dengan Linq kita boleh buat macam ni, lagi cool
// Query syntax
var shortBook = from x in BookList
where x.Length > 8
select $"printing book with more than 8 chracter: {x}";
foreach (string y in shortBook)
{
Console.WriteLine($"{y}");
}
sebenarnya LINQ ni ada dua jenis. Query Syntax. satu lagi Method Syntax
// Method Syntax
var longBook = BookList.Where(n => n.Length < 4).Select(n => $"this book has less than 4 character: {n}");
foreach (string book in longBook)
{
Console.WriteLine(book);
}
so korang suka yang macam Query atau Method syntax?
happy coding guys!
0
Subscribe to my newsletter
Read articles from consoleGuy directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by