2
var x = new {
    Name = "qwe",
    Options = someList.Select(x=>x.KEY).Select(x => 
        new {

            Title: someOtherList.FirstOrDefault(y => y.KEY == x) != null ? 
                   someOtherList.FirstOrDefault(y => y.KEY == x).Title : 
                   null
        }
    )
}).ToList();

我正在制作一个可序列化的对象列表。请查看我如何获取Title每个选项的属性。

我的问题是我获取的属性比标题多,并且条件运算符对每个属性都感觉非常过度。

有没有“更好”的写法?

4

3 回答 3

4

一个简单的解决方案是使用以下内容:

Title= someOtherList.Where(y => y.KEY == x).Select(x => x.Title).FirstOrDefault()

这正在执行以下操作:

  1. 从 someOtherList,返回那些Key等于的元素x
  2. 从这些元素中,选择Title.
  3. 返回第一个标题 - 或者null如果没有。
于 2013-06-28T10:54:22.947 回答
1

典型地,与原始代码最相似的方法是使用语句 lambda

Options = someList.Select(x=>x.KEY).Select(x => 
    {
        var other = someOtherList.FirstOrDefault(y => y.KEY == x);
        return new {
           Title = other == null ? null : other.Title
        };
    })
于 2013-06-28T11:08:30.670 回答
0

您可以改为调用方法:

Options = someList.Select(x=>x.KEY).Select(x => CreateObject(x, someOtherList));

public YourObject(or dynamic) CreateObject(YourObject x, List<SomeOtherObject> someOtherList)
{
    var other = someOtherList.FirstOrDefault(y => y.KEY == x);

    return new
    {
        Title = (other == null ? null : other.Title),
        Foo = (other == null ? null : other.Foo),
        ...
    }
}

或者使用@DarinDimitrov 显示的Linq 查询表达式let中的关键字完成相同的操作。

于 2013-06-28T10:57:29.367 回答