Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select Distinct List of Words from Array with LINQ

Tags:

c#

linq

distinct

I'm trying to get a distinct list of words from an array of words with the following code:

string words = "this is a this b";

var split = words.Split(' ');

IEnumerable<Word> distinctWords = (from w in split
                          select new Word
                                     {
                                         Text = w.ToString()
                                     }
                         ).Distinct().ToList();

I thought this would take out the double occurrence of 'this' but it returns a list of each word int he phrase.

Can somebody please suggest how I can go about getting a distinct list? Thanks

Dave

like image 989
DaveDev Avatar asked Feb 14 '10 00:02

DaveDev


People also ask

How to get distinct values from string array in c# using LINQ?

First, you need to get the partial strings. Then You reduce the resulting collections to one. Then split the individual strings by "=" and select only those that have "B" as first value and not "TestA" as second. Then select the second value and call Distinct , which removes duplicate values.

What does distinct do in LINQ?

C# Linq Distinct() method removes the duplicate elements from a sequence (list) and returns the distinct elements from a single data source. It comes under the Set operators' category in LINQ query operators, and the method works the same way as the DISTINCT directive in Structured Query Language (SQL).


1 Answers

In your example, each Word object is distinct, because there is no comparison which looks at the Text property.

However, there's no reason to create a new object:

var distinctWords = (from w in split 
                      select w).Distinct().ToList(); 

Or more simply:

var distinctWords = new List<string>(split.Distinct());
like image 86
James Curran Avatar answered Oct 07 '22 12:10

James Curran