استفاده از کالکشن های موقتی بدون تعریف آنها
بهتره برای فیلتر کردن لیست ها و به طور کلی کالکشن ها بسته به کاربرد از yield استفاده کنیم تا اینکه بخوایم یک لیست موقتی تشکیل بدیم، نتایج رو توش بریزیم و برگردونیم. به متدهای آورده شده در قسمت کد توجه کنید. اولی روش قدیمی و دومی روش اصولی هستش :)
// this the ancient method of filtering a collection :D public List<int> GetValuesGreaterThan100(List<int> masterCollection) { List<int> tempResult = new List<int>(); foreach (var value in masterCollection) { if (value > 100) tempResult.Add(value); } return tempResult; } // the following snippet is what recommended public IEnumerable<int> GetValuesGreaterThan100(List<int> masterCollection) { foreach (var value in masterCollection) { if (value > 100) yield return value; } }
نکته
Using yield instead of temporary collections in C#
نویسنده : محمد ملک مکان
شنبه 12 دی 1394
شنبه 12 دی 1394
ایده ها، نظرات و سوالات دوستان ما