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

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.

Related

LINQ sorting by number of appearances

I need to sort a list by numer od appearances and show repeating items only once. For example I have a following list : "a", "b", "a", "a", "c", "d", "c". I want it to be sorted like this: "a","c","b",d". How can I achieve this?
That is what I made:
var something = from c in db.Letters
group c by c.letter into p
orderby p.Count()
select new
{
p.letter
};
But expression p.letter cannot be used.
var resunt = from c in db.Letters
group c by c.letter into p
orderby p.Count() descending
select p.Key;
When you use GroupBy you get an IGroupping object that contains a property of the Key object that you've grouped by and a collection of the values in the group. In your case you want to return the Key - the c.letter

c# group by alphabets

I need to show list of authors group by last name first letter.
e.g.
A
Kim, Ami
Dim, Amaiar
jin, Amairaz
B
Bin, Bom
Kin, Bomo
C
Cin, Ci
Con, Co
....
Could some one please help me what's the best way to solve the above problem?
If you want to group by, use GroupBy, I assumed you want the output to be ordered (OrderBy), Change the GroupBy expression to match your exact requirment:
List<String> names = new List<String>{"Bill", "Mark", "Steve", "Amnon", "Benny"};
foreach(var g in names.GroupBy(name => name.First()).OrderBy(g => g.Key)){
Console.WriteLine(g.Key);
g.OrderBy(name => name).ToList().ForEach(Console.WriteLine);
}
Will output:
A
Amnon
B
Bill
Benny
M
Mark
S
Steve
You can use GroupBy extension method over Linq object to get the desire result.
List<string> firstNames = new List<string>(){ "Ami", "Amaiar","Amiraz","Bom","Bomo","Ci","Co" };
var groups = firstNames.GroupBy(x=>x[0]);
foreach (var element in groups)
{
Console.WriteLine("{0}", element.Key);
foreach (var word in element)
Console.WriteLine(" {0}", word);
}

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);

how to match string in a list

I'm having a list of string like
var target = new List<string>() { "C", "C-sharp", "java" };
I'm having a string request = "C is a programming language"
This list should match with the string and should return
C,C-sharp
How can i do this?
here is the solution with linq
var m = from t in target
where t[0] == 'C'
select t;
Using Linq and String.Contains:
var filtered = target.Where(str => str.Contains("C"));
Another option, without Linq, is to change the existing list using List<T>.RemoveAll:
target.RemoveAll(str => !str.Contains("C"));
If you really need a regex (for something more complex), you may also use:
Regex validate = new Regex(".a.", RegexOptions.IgnoreCase);
var filtered = target.Where(str => validate.Match(str).Success);

How do you count the words in an array of strings with 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

Resources