Reputation: 1003
I have some code that will loop over DataRow
s and will split a pipe delimited column in the DataRow
into an array, and then into a List<string>
.
Is there a better way to do this using LINQ? I've tried but got nowhere!
List<string> allSizes = new List<string>();
foreach (DataRow resultRow in results.Rows)
{
if (resultRow["Sizes"] != DBNull.Value)
{
string[] sizes = resultRow["Sizes"].ToString().Split('|');
foreach (string size in sizes)
{
if (!allSizes.Contains(size))
{
allSizes.Add(size);
}
}
}
}
Upvotes: 2
Views: 7139
Reputation: 15794
Strong-typed DataRow and LINQ:
dt.Rows.OfType<DataRow>().Where(r => r["Sizes"] != DBNull.Value)
.SelectMany(r=>r.Field<string>("Sizes").Split('|')
.Distinct().ToList();
Upvotes: 0
Reputation: 6546
Something like this.
var linqSizes =
from row in results.Rows
where row["Sizes"] != DBNull.Value
let sizes = row["Sizes"].ToString().Split('|')
from size in sizes
group size by size into g
select g.Key;
The variable linqSizes
will contain the same elements as your variable allSizes
.
Upvotes: 0
Reputation: 1713
Here is the LINQ version but personally I don't find it much cleaner:
var allSizes = new List<string>();
foreach (
string size in
from DataRow resultRow in results.Rows
where resultRow["Sizes"] != DBNull.Value
select resultRow["Sizes"].ToString().Split('|') into sizes
from size in sizes where !allSizes.Contains(size)
select size) {
allSizes.Add(size);
}
Upvotes: 0
Reputation: 203814
var allSizes = results.Rows.Cast<DataRow>()
.Where(row => row["Sizes"] != DBNull.Value)
.SelectMany(row => row["Sizes"].ToString().Split('|'))
.Distinct()
.ToList();
Upvotes: 10