gpt4 book ai didi

c# - 我可以/应该 Linqify 这个 foreach/if/foreach/if/invoke 代码吗?

转载 作者:行者123 更新时间:2023-11-30 13:40:27 30 4
gpt4 key购买 nike

我认为可以是 Linq 的代码:

    foreach (var key in _dic.Keys) // for each observed key
if (_changedKeys.Contains(key)) // if it changed
foreach (var item in _dic[key]) // then for each observer
if (_webSitePage.Session[key] != null) // , as long as the value is something
item(_webSitePage.Session[key]); // call the registered delegate

在周围代码的上下文中:

public class WebSiteContext
{
private WebSitePage _webSitePage;

internal void SetSessionValue<T>(string key, T value)
{
object current = _webSitePage.Session[key];
if (current != null && current.Equals(value)) return;
_webSitePage.Session[key] = value;
_changedKeys.Add(key);
}

Dictionary<string, List<Action<object>>> _dic = new Dictionary<string, List<Action<object>>>();

List<string> _changedKeys = new List<string>();

internal void WhenSessionValueChanges(string key, Action<object> action)
{
if (!_dic.ContainsKey(key)) _dic[key] = new List<Action<object>>(); // create on demand
_dic[key].Add(action);
}

internal void PageLoadComplete()
{
foreach (var key in _dic.Keys) // for each observed key
if (_changedKeys.Contains(key)) // if it changed
foreach (var item in _dic[key]) // then for each observer
if (_webSitePage.Session[key] != null) // , as long as the value is something
item(_webSitePage.Session[key]); // call the registered delegate

}
}

public class WebSitePage : System.Web.UI.Page
{
public WebSitePage()
{
this.WebSiteContext = new WebSiteContext(this);
}

public WebSiteContext WebSiteContext { get; set; }

protected override void OnLoadComplete(EventArgs e)
{
base.OnLoadComplete(e);
this.WebSiteContext.PageLoadComplete();
}
}

最佳答案

可以更改为 LINQ,但由于您调用 item(...) 是为了它的副作用,我认为在这里使用 LINQ 是不合适的,并且foreach 循环更好。

但是你可以这样写:

 foreach (var key in _dic.Keys.Where(key => _changedKeys.Contains(key))
{
foreach (var item in _dic[key])
{
var value = _webSitePage.Session[key];
if (value != null)
{
item(value);
}
}
}

关于c# - 我可以/应该 Linqify 这个 foreach/if/foreach/if/invoke 代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7854373/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com