How to correctly view the DistinctBy extension and ForEach extension of Linq

Source: Internet
Author: User

In Microsoft's standard Linq, there is no DistinctBy extension or ForEach extension, but these two functions are often used in daily work. In theory, microsoft should include these two extensions in Linq. But why not? In this article, I will talk about my understanding of these two extensions!

About DistinctBy Extension

As the name suggests, the DistinctBy extension is to filter unique elements based on a key value. Only one element with duplicate key values is retained! Of course, there are Distinct extensions in Linq, but their functions are simply weak! I believe all the comrades who have used it have been talking about Distinct expansion for countless times! If you want to use the Distinct extension to implement the DistinctBy Extension function, you also need to define a special helper class! Oh, My God! This is the murder of programmers! However, after numerous confusions, I suddenly found that Microsoft actually included the DistinctBy Extension function in standard Linq, but it was not so straightforward. Let's look at the following sample code:

 1 class Person 2         { 3             public int Age { get; set; } 4             public string Name { get; set; } 5             public override string ToString() 6             { 7                 return string.Format("Age:{0}  Name:{1}", Age, Name); 8             } 9         }10         [STAThread]11         static void Main()12         {13             var persons = new[] { 14                 new Person{Age = 10,Name="a"},15                 new Person{Age = 10,Name="b"},16                 new Person{Age = 10,Name="c"},17                 new Person{Age = 20,Name="d"}18             };19             foreach (var p in persons.GroupBy(o=>o.Age).Select(g=>g.First()))20             {21                 Console.WriteLine(p);22             }23         }

Running result

From the result, the Code successfully completed the Distinct operation based on the key value Age.

You may see it at a Glance. Good, it is to use the group by, Select, and First sub-operations to combine the DistinctBy function! It is not good to write the code to implement a DistinctBy function, so we can encapsulate the combination of the three sub-operations GroupBy, Select, and First into a DistinctBy extension method, this makes it easy to use. The encapsulated code too simple will not be pasted!

About ForEach Extension

Why does Microsoft not add the ForEach extension in Linq? There are already a lot of discussions on this issue on the Internet. The main reasons are as follows:

1. the Select extension already exists in Linq, so you don't need to implement a ForEach, because in most cases you can use Select to implement the ForEach function (of course I don't recommend doing this, because Select is a delayed operation, if you only implement the ForEach function, sometimes the Code cannot run correctly according to the design intent );

2. forEach destroys the programming mode of Linq. That is to say, it destroys the chain programming mode. The so-called chain programming means that multiple operations are passed through the dot ". "The links are all in one. I believe the comrades who have written this sentence are very clear about the meaning of this sentence!

I saw someone designing the ForEach extension on the Internet:

1 public static void ForEach<T>(this IEnumerable<T> source, Action<T> foreachAction)2         {3             foreach (var t in source)4             {5                 foreachAction(t);6             }7         }

I have to say that this is just a "foul" of Linq. Just imagine if someone else uses your ForEach, isn't it a fantasy to perform subsequent operations? Therefore, designing ForEach in this way is absolutely impossible! Even if you barely want to design it, you have to design it like this!

1 public static IEnumerable<T> ForEach<T>(this IEnumerable<T> source, Action<T> foreachAction)2         {3             foreach (var t in source)4             {5                 foreachAction(t);6             }7             return source;8         }

In my opinion, it is not appropriate to add the ForEach extension because:The ForEach extension designed in this way breaks the delay Operation Feature of Linq!

Therefore, I think that it is a correct choice for Microsoft not to include the ForEach extension in Linq. If you want to use the ForEach function, you should write the foreach statement honestly! It's not complicated!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.