Temporary variable inside anonymous type

I have a linq statement similar to the following:

        var entities = from row in table.AsEnumerable()
                                    select new
                                    {
                                        ID = row.ID,
                                        X = GetObjectByProcessingID(row.ID)[0],
                                        Y = GetObjectByProcessingID(row.ID)[1],
                                        ....
                                    };

Is it possible to do something like:

        var entities = from row in table.AsEnumerable()
                                    select new
                                    {
                                        private var tmp = GetObjectByProcessingID(row.ID),
                                        ID = row.ID,
                                        X = tmp[0],
                                        Y = tmp[1],
                                        ....
                                    };

To call GetObjectByProcessingID twice?

I know you can do something like:

        var entities = from row in table.AsEnumerable()
                                    select new
                                    {
                                        ID = row.ID,
                                        XAndY = GetObjectByProcessingID(row.ID),
                                        ....
                                    };

But in this case, it will output the whole array. I also know that I can implement things like method-side caching (GetObjectByProcessingID) or create a helper method to call it and remember the last value if the identifier is the same. But is there a better way? Can I create temporary variables when creating an anonymous type?

+4
source share
1 answer

Use the keyword letas follows:

var entities = from row in table.AsEnumerable()
               let tmp = GetObjectByProcessingID(row.ID)
               select new {
                            ID = row.ID,
                            X = tmp[0],
                            Y = tmp[1],
                            ....
                           };

method syntax, :

var entities = table.AsEnumerable()
                    .Select(row => {
                       var tmp = GetObjectByProcessingID(row.ID);
                       return new {
                                ID = row.ID,
                                X = tmp[0],
                                Y = tmp[1],
                                ....
                              };
                     });
+11

All Articles