score:11
Have you tried a simple join?..
if field.Values is already an array of strings then this should work fine.. otherwise you could use LINQ .ToArray()
to convert the collection to an array.
string joined = string.Join(Environment.NewLine, field.Values);
VB
Dim joined As String = String.Join(Environment.NewLine, field.Values)
Just figured I would add, if you really, really just wanted to do this with LINQ a Aggregrate would work, although I wouldn't really recommend this for your needs.
field.Values.Aggregate(string.Empty, (s1, s2) => s1 += Environment.NewLine + s2);
score:0
If Values
is a List you can do this...
field.Values.ForEach(o=>fileContent.Append(o + Environment.NewLine));
score:2
I created these extension methods that can be used to concatenate any number of items in a collection. It may be a bit overkill for you example, but if you need to concatenate items that are objects and not strings it can work great.
Usage:
fileContent = field.Values.Contatenate(Environment.NewLine);
Extensions:
public static class EnumerableExtensions
{
public static string Concatenate<T>(this IEnumerable<T> source, string seperator)
{
return Concatenate(source, i => i.ToString(), seperator);
}
public static string Concatenate<T>(this IEnumerable<T> source, Func<T, string> selector, string seperator)
{
var builder = new StringBuilder();
foreach (var item in source)
{
if (builder.Length > 0)
builder.Append(seperator);
builder.Append(selector(item));
}
return builder.ToString();
}
public static string ToCsv<T>(this IEnumerable<T> source)
{
return Concatenate(source, i => i.ToString(), ",");
}
public static string ToCsv<T>(this IEnumerable<T> source, Func<T, string> selector)
{
return Concatenate(source, selector, ",");
}
}
score:1
You can use the Aggregate method to get there, but it won't be nearly as efficient as a foreach loop that Appends to a file or StringBuilder.
I believe your basic issue is that Linq's proper usage is to return results. The designers did not intend for you to use a Linq statement to modify the objects it is iterating through. That likely explains the general difficulty you've had with this task.
Don't forget that foreach is a proper way to use Linq results!
score:0
You may want to use IEnumerable.Aggregate.
Your code will look something like this:
Dim fileContentString As String = _
field.Values.Aggregate(Function(ByVal JoinedValues, ByVal DiscreteValue)
JoinedValues & Environment.NewLine & DiscreteValue)
Disclaimer - Just because you CAN use Linq, doesn't mean it's the right tool for this job. As others have pointed out, a ForEach loop would be more efficient.
score:1
You can use a StringBuilder in the Aggregate extension method:
Dim fileContent As String = _
field.Values.Aggregate( _
New StringBuilder(), _
Function(b, i) b.AppendLine(i) _
).ToString()
score:0
Create an extension method -
<Extension()> _
Public Function Flatten(ByVal stringList As IList(Of String), ByVal delimiter As String) As String
Dim strB As New StringBuilder
For Each Str As String In stringList
If strB.ToString.Length > 0 Then
strB.Append(delimiter)
End If
strB.Append(Str)
Next
Return strB.ToString
End Function
Once you have that, you can simple do what you want like this -
Dim letters as New List(Of String)
'do your loading of the list
Dim formattedString As String = letters.Flatten(Environment.NewLine)
score:1
Note that .NET 4.0 includes a new String.Concat<T>() static method which takes an IEnumerable<T>
and calls ToString on each object in the list. Should come in handy!
Source: stackoverflow.com
Related Articles
- How can I build a string from a collection with Linq?
- Find a certain value from a source collection in a target collection of different type with linq
- Linq to update a collection with values from another collection?
- using LINQ how can i concatenate string properties from itesm in a collection
- Select only subclasses from collection with Linq
- How to select multiple columns from dataset into a string list with LinQ
- How to select distinct employees with LINQ based on ID from an employee collection where employee 's salary is 2nd highest?
- Dynamically build up a linq query with hierarchy using string field names?
- creating Linq to sqlite dbml from DbLinq source code
- get sublist from list, and build average, with linq
- Removing from a collection while in a foreach with linq
- Get objects from collection with Linq
- Retrieve strings from a file, filtering with Linq when multiple lines contain the exact same string
- Linq to objects - Search collection with value from other collection
- Can't add a new record with an integer value into database by using linq from code C#
- How to order a collection with LINQ so that a particular string appears first
- Concatenate collection of XML tags to string with LINQ
- How to build a LINQ expression with Contains method from IEnumerable?
- How to write a LINQ query to select from a collection with given set of matching IDs
- With LINQ how do you return a string const in the result from the select operator
- How can I add and remove records from a collection with LINQ
- extract data from JSON string with LINQ request
- Build a query from a string with values that varies
- How to join MongoDB collection with string[] on collection with string using Linq
- Select all fields from collection with related items in another collection using LINQ
- Select maximum version from collection with LINQ in EF
- Linq Concating a list of tags with count from an inner collection of an outer collection
- Is it right a LINQ query to check whether atleast one entity exists in string collection with a matching criteria (rownum<=1)
- problem with converting the output from linq query to string
- Convert a collection of objects with a string property to an enumeration of those strings using LINQ
- Group List of Dictionaries by a Dictionary-key (C#)
- Return list of rows that match a list of values using LINQ
- C# DateTime down to the minute from linq
- Check if value is in another table
- How to select nested xml nodes into Model
- LINQ to EF Sub query
- using linq to merge items together in a collection
- How to convert this to Linq?
- Create TreeNodes with key in a Linq expression
- Create a Linq to entities IQueryable extension for date grouping (GroupBy)
- Is there anything special in how LINQ query handles references to objects?
- Select Min and Max LINQ
- Filter the numbers of records returned from two collections
- Nested LiNQ to XML
- How to sum a single row with multiple columns in linq query
- Using Linq to group a list of objects that contains primitives data into a new grouped list of objects
- How to update value in a List using LINQ
- linq - find item in list within multiple lists
- Cannot access or find reference to System.Xml.Linq.LineInfoAnnotation. Why is this?
- Linq and EF: Querying to get results on one to many relationships: Selecting table with foreign Key