LINQ equivalent of foreach for IEnumerable

后端 未结 22 2260
夕颜
夕颜 2020-11-21 22:54

I\'d like to do the equivalent of the following in LINQ, but I can\'t figure out how:

IEnumerable items = GetItems();
items.ForEach(i => i.DoS         


        
22条回答
  •  情歌与酒
    2020-11-21 23:42

    Inspired by Jon Skeet, I have extended his solution with the following:

    Extension Method:

    public static void Execute(this IEnumerable source, Action applyBehavior, Func keySelector)
    {
        foreach (var item in source)
        {
            var target = keySelector(item);
            applyBehavior(target);
        }
    }
    

    Client:

    var jobs = new List() 
        { 
            new Job { Id = "XAML Developer" }, 
            new Job { Id = "Assassin" }, 
            new Job { Id = "Narco Trafficker" }
        };
    
    jobs.Execute(ApplyFilter, j => j.Id);
    

    . . .

        public void ApplyFilter(string filterId)
        {
            Debug.WriteLine(filterId);
        }
    

提交回复
热议问题