1

By far the most calls to LINQ in my C# programs look like

var SomeCollection = OriginalCollection.Select( x => x.Surname );

Is there some clever way to make it even more concise? Something like (or better):

var SomeCollection = OriginalCollection.Select( ^.Surname );

Surely there are a lot of lines like this, lambda could be implicit in calls like the above (and argument name set to some default char). Or maybe something even more weird like OriginalCollection.Surname.

Radost
  • 309
  • 3
  • 11

2 Answers2

1

There is nothing wrong with x => x.property syntax. It is like that in other languages like ES6 / Typescript. Shorthanding it further does not make much sense (save 1-2 characters?). Not where your refactoring thoughts should be going anyway. Instead, think at higher level, and try to save on statements, rather than characters. If you have to write the same code over and over again, stop and think, there is likely a better way. For example, if you repeat 1 line in 5 places, it might be bad, but repeating a block of 10 lines in 5 places is much worse.

In an ideal application, each code should be repeated once. More repetition - more difficult to maintain, harder to change. Less repetition - more complex architecture, easier to change, but need more senior developers. Usually it's about the balance between the two. With a very simple goal - being able to deliver business need, on time and on budget.

Victor Zakharov
  • 25,801
  • 18
  • 85
  • 151
0

Yea, not like your suggestions, but if you have a lot of them chained you might like to use Basic LINQ Query Operations (C#).

var queryLondonCustomers3 =
    from cust in customers
    where cust.City == "London"
    orderby cust.Name ascending
    select cust;

or

var SomeCollection = from x in OriginalCollection select x.Surname;
Patrick Beynio
  • 788
  • 1
  • 6
  • 13