using System; using System.Collections.Generic; using System.Linq;
namespaceConsoleApp { classProgram { staticvoidMain(string[] args) { var members = new List<Member> { new Member {Username = "Sam", Password = "1234"}, new Member {Username = "You", Password = "4567"} };
var user = new Member {Username = "Sam", Password = "1234"};
var member = members .Where(x => x.Username == user.Username && x.Password == user.Password) .FirstOrDefault(); string result; if (member != null) { result = member.Username; } else { result = ""; } Console.WriteLine($"Welcome {result}"); } } }
19 行
1 2 3
var member = members .Where(x => x.Username == user.Username && x.Password == user.Password) .FirstOrDefault();
大部分人會採用 Where() 搭配 FirstOrDefault() 寫法。
25 行
1 2 3 4 5 6 7 8
if (member != null) { result = member.Username; } else { result = ""; }
using System; using System.Collections.Generic; using System.Linq; usingstatic System.Console;
namespaceConsoleApp { classProgram { staticvoidMain(string[] args) { var members = new List<Member> { new Member {Username = "Sam", Password = "1234"}, new Member {Username = "You", Password = "4567"} };
var user = new Member {Username = "Sam", Password = "1234"};
members .Where(IsMember(user)) .DefaultIfEmpty(DefaultMember()) .Select(ToFormat) .ToList() .ForEach(WriteLine);
由於使用了 DefaultIfEmpty(),我們就不用再判斷 null ,可以使用 FP 的 Data Flow 方式加以處理,完全 Pure Function 沒有 Side Effect,直到最後 Select() 完,才呼叫 ForEach() 執行 Side Effect 的 WriteLine