Linq to create a csv string for some values stored in an array of object using c#
I have an array of object storing some accounts.
12345631
L1234512
P12345
234556
1909开发者_JS百科0912
J123456
Using Linq and .Net 3.5, I want to create a csv string for accounts starting with L or P and is of 6 characters. Following code creates a csv string but how to add the filter?
string[] accounts = accountList.Select(c => c.acctnbr).ToArray();
string csv = string.Join(",", accounts);
The output should be L12345,P12345
.
Try this:
string[] accounts = accountList
.Where
(
a=> (a.acctnbr.StartsWith("L") || a.acctnbr.StartsWith("P"))
&&
(a.acctnbr.Length == 6)
)
.Select(c => c.acctnbr)
.ToArray();
string csv = string.Join(",", accounts);
In case you't interested, here's a version using the query syntax instead as well
var accounts = from a in accountList
where (a.acctnbr.StartsWith("L") || a.acctnbr.StartsWith("P"))
&& (a.acctnbr.Length == 6)
select a.acctnbr;
var csv = String.Join("," accounts.ToArray());
Based on the comment you added regarding which solution is better, mine or Cybernate. The solutions are the same, C# let's you write queries in two ways. You can take a look at LINQ Query Syntax versus Method Syntax (C#) for more information.
Relevant bit from ducumentation (though I would strongly urge you to read up more on Linq)
In general, we recommend query syntax because it is usually simpler and more readable; however there is no semantic difference between method syntax and query syntax. In addition, some queries, such as those that retrieve the number of elements that match a specified condition, or that retrieve the element that has the maximum value in a source sequence, can only be expressed as method calls.
string[] accounts = accountList.Select(c => c.acctnbr).ToArray();
IEnumerable<string> namesWithFourCharacters = from name in accounts
where name.StartsWith("L")
select name;
Hope this helps.
精彩评论