Is there any way to convert a collection of objects into a single new object using LINQ?
I want to use this within another LINQ to SQL expression.
Is there any way to convert a collection of objects into a single new object using LINQ?
I want to use this within another LINQ to SQL expression.
The normal way would be to use one of the aggregation operators (Aggregate
, Sum
, Average
etc), but it entirely depends on the type and what you want to do. What type are you interested in?
EDIT: Okay, so you want to concatenate strings... I don't think there's anything which will do that in LINQ to SQL itself. Options:
Why don't you use the string.Join
itself?
string.Join("<br/>", collection.Select(e => e.TextProp).ToArray());
You can use the Aggregate method...
var myResults = (from myString in MyStrings
select myString)
.Aggregate(string.Empty, (results, nextString)
=> string.Format("{0}<br />{1}", results, nextString));
Most of the solutions here are fairly inefficient if you have large numbers of values you want to concatonate. Also, they're not all that readable. If you are going to do this sort of thing frequently, then it's worth building your own extension method to do it. The implementation below allows you to do the equivalent of string.Join(", ", arrayOfStrings)
where the arrayOfStrings can be an IEnumerable<T>
, and separator can be any object at all. It allows you to do something like this:
var names = new [] { "Fred", "Barney", "Wilma", "Betty" };
var list = names
.Where(n => n.Contains("e"))
.Join(", ");
Two things I like about this are:
public static string Join<TItem,TSep>(
this IEnumerable<TItem> enuml,
TSep separator)
{
if (null == enuml) return string.Empty;
var sb = new StringBuilder();
using (var enumr = enuml.GetEnumerator())
{
if (null != enumr && enumr.MoveNext())
{
sb.Append(enumr.Current);
while (enumr.MoveNext())
{
sb.Append(separator).Append(enumr.Current);
}
}
}
return sb.ToString();
}