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
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.
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).
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With