Convert anonymous type to new C# 7 tuple type

前端 未结 5 1964
情书的邮戳
情书的邮戳 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 16:56

    Note for anyone on a lower version of .NET: If you are on a lower version of .NET than 4.7.2 or .NET Core, you should use Nuget Package Manager to install System.ValueTuple to your project.

    Then, here's an example of getting a tuple from a Linq to SQL query:

    var myListOfTuples = (from record1 in myTable.Query()
                         join record2 in myTable2.Query() on record1.Id = record2.someForeignKey
                         select new {record1, record2}).AsEnumerable()
                         .select(o => (o.record1, o.record2))
                         .ToList()
    

    That ran for me, however, after check-in, I got a build failure...read on.

    For even more fun and games, I unfortunately had an earlier version of C# on my build server for some reason. So I had to go back because it didn't recognize the new tuple format on the .select(o => (o.record1, o.record2)) line (specifically that it would be a tuple because of the parenthesis around o.record1 and o.record2). So, I had to go back and kind of finagle it a bit more:

    var myListOfAnonymousObjects = (from record1 in myTable.Query()
                         join record2 in myTable2.Query() on record1.Id = record2.someForeignKey
                         select new {record1, record2}).ToList()
    
    var myTuples = new List>();
    foreach (var pair in myListOfAnonymousObjects)
    {
        myTuples.Add(pair.record1, pair.record2);
    }
    return myTuples;
    

提交回复
热议问题