Using linq to build a comma delimited string - linq

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

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

LINQ create multiple new entities using a single ID field

I have a newbie LINQ question. I need to create two objects of same type from a list of strings. I need to append a text 'Direct' & "Indirect' to the string and use them as ID to create the two unique objects.
var vStrings = new List { "Milk", "Eggs", "Cheese" };
var vProducts = (from s in vStrings
select new Product { ID = s + "-Direct" })
.Union(
from s in vStrings
select new Product { ID = s + "-InDirect" });
You can see in the example above, I am using a Union to create two different objects, Is there a better way to rewrite this LINQ query?
Thanks for your suggestions
If you ever needed more suffixes, this might be a better way:
var strings = new List<string> { "Milk", "Eggs", "Cheese" };
var suffixes = new List<string> {"-Direct", "-InDirect"};
var products = strings
.SelectMany(_ => suffixes, (x, y) => new Product() {ID = x + y});
And it would only iterate over the original set of strings once.
This way isn't much shorter but I think it would be a little better such as there is only one Concat instead of many Union:
var vProducts2 = (from s in vStrings
select s + "-Direct").Concat(
from s in vStrings
select s + "-InDirect");

How can I filter nested lists with Linq?

I use LINQ on a Dictionary<string, IList<ID>> like this:
var searchCategories = new List {"A", "B", "C"};
Result = CategoryMapper.Mapping.Where(
x => searchCategories.Contains(x.Key)).
Select(x => new Tuple<string, IList<ID>>(x.Key, x.Value)).ToList();
This returns all ids that are either in Category A, B or C. However what I would like to do is retrieve ids that are in Category A, B and C.
I'm having difficulties figuring out how to do this with Linq.
UPDATE
I'm sorry but I should have added some more information in my initial post. The lists in my dictionary look somewhat like this (I only use numbers here to make it simple):
A : {1, 2, 3}
B : {1,3}
C : {3}
So what I would like as a result of my query would be '3' in this case because it is the only number that has all categories.
Looks like you're just taking the intersection of all the lists. That should be simple to obtain.
var searchCategories = new HashSet<string> { "A", "B", "C" };
var result = CategoryMapper.Mapping
.Where(map => searchCategories.Contains(map.Key))
.Select(map => map.Value as IEnumerable<ID>)
.Aggregate((acc, cur) => acc.Intersect(cur));
If your ID type doesn't implement the IEquatable<ID> interface, then you may need to provide an equality comparer (that I assume you have) to perform the comparisons.
....Aggregate((acc, cur) => acc.Intersect(cur, new YourIdEqualityComparer()));
You can try to change x => searchCategories.Contains(x.Key) to x => searchCategories.All(c => x.Key.Contains(c)), i.e. the final code snippet should be
var searchCategories = new List<string> {"A", "B", "C"};
Result = CategoryMapper.Mapping.Where(
x => searchCategories.All(c => x.Key.Contains(c))).
Select(x => new Tuple<string, IList<ID>>(x.Key, x.Value)).ToList();
To get all the ids, the SelectMany method is perfect for this:
var ids = CategoryMapper.Mapping.SelectMany(kv => kv.Value);

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

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