如何格式化复杂的 linq 表达式?

我有一种怪物的linq表情:


public static class HeaderOperators

{

    public static IDictionary<string, string> GetValues(IReadOnlyList<string> keys, IHeaderDictionary headers, string defaultValue)

    {

        return keys.Select(x => x.ToLower()).Intersect(headers.Keys.Select(x => x.ToLower()))

            .Select(k => new KeyValuePair<string, string>(k.ToLower(), headers[k.ToLower()]))

            .Union(keys.Select(x => x.ToLower()).Where(k => !headers.Keys.Select(x => x.ToLower()).Contains(k.ToLower())).Select(k => new KeyValuePair<string, string>(k.ToLower(), defaultValue)))

            .ToDictionary(p => p.Key.ToLower(), p => p.Value);

    }

}

有没有可用的工具可以很好地格式化它以便于阅读?


或者,也许有一种更易于管理的语法?


弑天下
浏览 83回答 2
2回答

月关宝盒

我会将其拆分以使其更具可读性:public static class HeaderOperators{&nbsp; &nbsp; public static IDictionary<string, string> GetValues(IReadOnlyList<string> keys, IHeaderDictionary headers, string defaultValue)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var firstCollection = keys&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Select(x => x.ToLower()).Intersect(headers.Keys.Select(x => x.ToLower()))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Select(k => new KeyValuePair<string, string>(k.ToLower(), headers[k.ToLower()]));&nbsp; &nbsp; &nbsp; &nbsp; var secondCollection = keys&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Select(x => x.ToLower())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Where(k => !headers.Keys.Select(x => x.ToLower()).Contains(k.ToLower()))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Select(k => new KeyValuePair<string, string>(k.ToLower(), defaultValue));&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; firstCollection.Union(secondCollection).ToDictionary(p => p.Key.ToLower(), p => p.Value);&nbsp; &nbsp; }}

大话西游666

由于它比嵌套更连锁,我只需将其格式化为如下所示:return&nbsp;keys.Select(&nbsp;x&nbsp;=>&nbsp;x.ToLower()&nbsp;) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.Intersect(&nbsp;headers.Keys.Select(x&nbsp;=>&nbsp;x.ToLower())&nbsp;) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.Select(&nbsp;k&nbsp;=>&nbsp;new&nbsp;KeyValuePair<string,&nbsp;string>(k.ToLower(),&nbsp;headers[k.ToLower()])&nbsp;) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.Union(&nbsp;keys.Select(x&nbsp;=>&nbsp;x.ToLower()&nbsp;) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.Where(&nbsp;k&nbsp;=>&nbsp;!headers.Keys.Select(x&nbsp;=>&nbsp;x.ToLower()).Contains(k.ToLower())&nbsp;) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.Select(&nbsp;k&nbsp;=>&nbsp;new&nbsp;KeyValuePair<string,&nbsp;string>(k.ToLower(),&nbsp;defaultValue))&nbsp;) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.ToDictionary(&nbsp;p&nbsp;=>&nbsp;p.Key.ToLower(),&nbsp;p&nbsp;=>&nbsp;p.Value&nbsp;);并且...在每行末尾添加注释。
打开App,查看更多内容
随时随地看视频慕课网APP