使用lambda表达式的LINQ查询

时间:2016-02-04 03:29:12

标签: c# asp.net .net linq lambda

我有这个linq查询,它工作正常,但我想通过使用lambda表达式缩短它。任何建议或示例都可能有所帮助。

selectedPersons = (from d in entities.PERSONS_DATA
                   where d.PERSON_ID == pid
                   select d).First();

2 个答案:

答案 0 :(得分:2)

selectedPersons = entities.PERSONS_DATA.First (d => d.PERSON_ID == pid);

答案 1 :(得分:0)

如果可以使用:

electedPersons = entities.PERSONS_DATA.FirstOrDefault(d => d.PERSON_ID == pid);

if(electedPersons != null)
   ....

如果pid可能与行不匹配,则First会抛出异常。所以在这种情况下使用:

var subscription = Observable.Create<IObservable<YourType>>(o =>
{
    var current = groups.Replay();
    var connection = new SerialDisposable();
    connection.Disposable = current.Connect();

    return IsSubscribed
        .DistinctUntilChanged()
        .Select(isRunning =>
        {
            if (isRunning)
            {
                //Return the current replayed values.
                return current;
            }
            else
            {
                //Disconnect and replace current.
                current = source.Replay();
                connection.Disposable = current.Connect();
                //yield silence until the next time we resume.
                return Observable.Never<YourType>();
            }

        })
        .Subscribe(o);
})
.Switch()
.Subscribe(o => Insert(o.Type, o.List));