Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Temporary variable inside anonymous type

Tags:

c#

linq

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],
                                        ....
                                    };

Would it be 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 avoid calling 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 expose the whole array. I also know that I can implement stuff like caching on the method side (GetObjectByProcessingID) or creating a helper method to call it and remember the last value if the ID is the same. But is there a better way? Can I create temporary variables while creating the anonymous type?

like image 413
David Avatar asked Dec 20 '22 22:12

David


1 Answers

Use the let keyword like this:

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

You can also try using method syntax which is very favorite to me:

var entities = table.AsEnumerable()
                    .Select(row => {
                       var tmp = GetObjectByProcessingID(row.ID);
                       return new {
                                ID = row.ID,
                                X = tmp[0],
                                Y = tmp[1],
                                ....
                              };
                     });
like image 76
King King Avatar answered Dec 22 '22 10:12

King King