Convert anonymous type to new C# 7 tuple type

前端 未结 5 1965
情书的邮戳
情书的邮戳 2021-01-07 16:19

The new version of C# is there, with the useful new feature Tuple Types:

public IQueryable Query();

public (int id, string name) GetSomeIn         


        
5条回答
  •  迷失自我
    2021-01-07 17:10

    Of course, by creating the tuple from your LINQ expression:

    public (int id, string name) GetSomeInfo() {
        var obj = Query()
            .Select(o => (o.Id,o.Name))
            .First();
    
        return obj;
    }
    

    According to another answer regarding pre-C# 7 tuples, you can use AsEnumerable() to prevent EF to mix things up. (I have not much experience with EF, but this should do:)

    public (int id, string name) GetSomeInfo() {
        var obj = Query()
            .AsEnumerable()
            .Select(o => (o.Id,o.Name))
            .First();
    
        return obj;
    }
    

提交回复
热议问题