Reputation: 159
new with Linq and very excited with this feature. However, I want to see if I can do the following with LINQ:
DataView source = (DataView) MyDataGrid.ItemsSource;
foreach (DataRowView vw in source)
{
if (vw.Row[dummyColumnIndex] != null &&
vw.Row[dummyColumnIndex].ToString() == DisplayValue)
{
vw.Row[dummyColumnIndex] = string.Empty;
break;
}
}
Notice that I have a break in my foreach loop, meaning that I just need to reset the first match row's column value to empty string.
Thanks!
Upvotes: 2
Views: 1286
Reputation: 10389
Yes it can. I tend to prefer the query syntax:
var query = from vw in source.Cast<DataRowView>()
where vw.Row[dummyColumnIndex] != null &&
vw.Row[dummyColumnIndex].ToString() == DisplayValue
select vw;
var item = query.FirstOrDefault();
if (item != null)
item.Row[dummyColumnIndex] = "";
As noted by others: its best to use 'FirstOrDefault' to avoid throwing an exception if you don't find a match.
Upvotes: 2
Reputation: 1734
If the Objective is to find something in a list
{
if (sorted) http://en.wikipedia.org/wiki/Search_algorithms
else if(efficent) http://en.wikipedia.org/wiki/Sort_algorithms
else i don`t know
}
Upvotes: 0
Reputation: 144136
var firstMatch = source
.Cast<DataRowView>()
.First(vw => vw.Row[dummyColumnIndex] != null && vw.Row[dummyColumnIndex].ToString() == DisplayValue);
firstMatch.Row[dummyColumnIndex] = string.Empty;
Note that this will throw an exception if there's no match, so you could also do:
var firstMatch = source
.Cast<DataRowView>()
.FirstOrDefault(vw => vw.Row[dummyColumnIndex] != null && vw.Row[dummyColumnIndex].ToString() == DisplayValue);
if(firstMatch != null)
firstMatch.Row[dummyColumnIndex] = string.Empty;
Upvotes: 1
Reputation: 2386
Yes, but you'll need to use the Cast method of IEnumerable to cast this over to a generic IEnumerable where the Type argument is 'DataRowView', then you can do something like this. This will use the provided logic (in the form of a lambda expression) to evaluate each record in the DataView to determine if it's a match. It'll return the first one it finds, or 'null' if none are found. You can handle the null anyway you want; I usually like to throw exceptions in case like that unless there's a valid reason that no match might be found.
var match = source.Cast<DataRowView>().FirstOrDefault(
s => s[dummyColumnIndex] != null &&
s[dummyColumnIndex].ToString() == DisplayValue);
if (match == null)
throw new Exception("Could not find match for " + DisplayValue);
match[dummyColumnIndex] = String.Empty;
Upvotes: 4