How do you count the words in an array of strings with LINQ? - linq

Given an array like {"one two", "three four five"}, how'd you calculate the total number of words contained in it using LINQ?

You can do it with SelectMany:
var stringArray = new[] {"one two", "three four five"};
var numWords = stringArray.SelectMany(segment => segment.Split(' ')).Count();
SelectMany flattens the resulting sequences into one sequence, and then it projects a whitespace split for each item of the string array...

I think Sum is more readable:
var list = new string[] { "1", "2", "3 4 5" };
var count = list.Sum(words => words.Split().Length);

Or if you want to use the C# language extensions:
var words = (from line in new[] { "one two", "three four five" }
from word in line.Split(' ', StringSplitOptions.RemoveEmptyEntries)
select word).Count();

Not an answer to the question (that was to use LINQ to get the combined word count in the array), but to add related information, you can use strings.split and strings.join to do the same:
C#:
string[] StringArray = { "one two", "three four five" };
int NumWords = Strings.Split(Strings.Join(StringArray)).Length;
Vb.Net:
Dim StringArray() As String = {"one two", "three four five"}
Dim NumWords As Integer = Split(Join(StringArray)).Length

Related

Modifying an array in Swift 2

shoppingList[4...6] = ["Bananas", "Oranges"]
Don't use subscript syntax to append a new item to an array.
But I realize append one or more new items to array with ranges successed. For example:
var shoppingList : Array<String> = ["Bread", "Milk", "Blackingbar", "Chian", "baba", "Oppo", "Xiaomi"]
shoppingList[4...6] = ["Bananas", "Oranges", "Huewei", "5", "6"]
for obj in shoppingList {
print(obj)
}
Why we have recommeded "don't use it" ????
The precise quote from the documentation is
You can’t use subscript syntax to append a new item to the end of an
array.
Your code example replaces three items at index 4 - 6 with five other items simultaneously which is something different. As far as the subscripted range is not out of bounds the operation succeeds.
Im not sure why you would want to make 5 items replace the last 3 but if you need to do it, you could do this:
var shoppingList : Array<String> = ["Bread", "Milk", "Blackingbar", "Chian", "baba", "Oppo", "Xiaomi"]
shoppingList = shoppingList[0..<4] + ["Bananas", "Oranges", "Huewei", "5", "6"]

Linq: Produce one result from two linq sources

I have two linq statements which both prouce an output of the same tye. How do can I merge this two linqstatements into, so that I get a single list.
Example:
var list1 = new List<string>() {"hello", "world", "!"};
var list2 = new List<string>() {"hello 2", "world 2", "! 2"};
var linq1 = from item in list1
where item.Contains('o')
select item;
var linq2 = from item in list2
where item.Contains('l')
select item;
var joined = linq1.Concat(linq2);
Output:
[0]: "hello"
[1]: "world"
[2]: "hello 2"
[3]: "world 2"
I want to have this in a single linq statement.
You just use Concat as you have. But instead of linq.Concat(linq2), you just put the queries there:
var joined = list1.Where (w => w.Contains("o"))
.Concat(list2.Where (w => w.Contains("l")));
Concat doesnt have a query syntax equivalent. (http://msdn.microsoft.com/en-us/library/bb386979(v=vs.110).aspx)
So you'd do something like this:
var joined = (from item in list1
where item.Contains('o')
select item)
.Concat(from item in list2
where item.Contains('l')
select item);

Using linq to build a comma delimited string

I need to generate a string that has a comma delimited list, but no comma after the last element.
var x = new List<string>() { "a", "b", "c" };
should yield:
a,b,c
Yes, a very simple thing to do using "normal" techniques, but I hope with linq there is a more elegant way.
var cols =context.Database.SqlQuery<String>("select Column_Name from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = {0};", prefix + table);
No need Linq, just use String.Join
String.Join(",", new List<string>() { "a", "b", "c" });
String class provide Join method to join string array with delimiter.
Code:
var x = new List<string>() { "a", "b", "c" };
String.Join(",",x.ToArray());
documentation: http://msdn.microsoft.com/en-us/library/57a79xd0(v=vs.110).aspx
Although I strongly recommend you use the answer of Siva Charan, just for information here's an implementation in LinQ using Enumerable.Aggregate Method (IEnumerable, Func):
var result = x.Aggregate((c, n) => c + "," + n);

Linq List contains specific values

I need to know if the List I am working with contains only some specific values.
var list = new List<string> { "First", "Second", "Third" };
If I want to know if the List contain at least one item with the value "First" I use the Any keyword:
var result = list.Any(l => l == "First");
But how I can write a Linq expression that will return true/false only if the List contains "First" and "Second" values?
I'm not entirely sure what you want, but if you want to ensure that "First" and "Second" are represented once, you can do:
var result = list.Where(l => l == "First" || l =="Second")
.Distinct()
.Count() == 2;
or:
var result = list.Contains("First") && list.Contains("Second");
If you've got a longer "whitelist", you could do:
var result = !whiteList.Except(list).Any();
On the other hand, if you want to ensure that all items in the list are from the white-list and that each item in the white-list is represented at least once, I would do:
var set = new HashSet(list);
set.SymmetricExceptWith(whiteList);
var result = !set.Any();
EDIT: Actually, Jon Skeet's SetEquals is a much better way of expressing the last bit.
Your question is unclear.
From the first sentence, I'd expect this to be what you're after:
var onlyValidValues = !list.Except(validValues).Any();
In other words: after you've stripped out the valid values, the list should be empty.
From the final sentence, I'd expect this:
var validSet = new HashSet<string>(requiredValues);
var allAndOnlyValidValues = validSet.SetEquals(candidateSequence);
Note that this will still be valid if your candidate sequence contains the same values multiple times.
If you could clarify exactly what your success criteria are, it would be easier to answer the question precisely.
You can use Intersect to find matches:
var list = new List<string> { "First", "Second", "Third" };
var comparelist = new List<string> { "First", "Second" };
var test = list.Intersect(comparelist).Distinct().Count() == comparelist.Count();

Linq: join the results in a IEnumerable<string > to a single string

how do i join the results in a IEnumerable to a single string?
the IEnumerable contains 20 single letters, and i want it to combine it to a single string.
And out of curiousity: how would i join it with a separator, for example if the IEnumerable contains the strings a b c d e how can i join it to a,b,c,d,e?
Michel
Try this:
IEnumerable<string> letters = new[] { "a", "b", "c", "d", "e" };
string separator = ", ";
string withSeparator = String.Join(separator, letters.ToArray());
string withoutSeparator = String.Join(String.Empty, letters.ToArray());
Also, with 4.0 .NET there's a new simpler overload available: String.Join Method (String, IEnumerable<String>) so you can skip the ToArray() call.

Resources