开发者

Search in a List<DataRow>?

I have a List which I create from a DataTabe which only has one column in it. Lets say the column is called MyColumn. Each element in the list is an object array containing my columns, in this case, only one (MyColumn). Whats the most elegant way to check if that obj开发者_Go百科ect array contains a certain value?


var searchValue = SOME_VALUE;
var result = list.Where(row => row["MyColumn"].Equals(searchValue)); // returns collection of DataRows containing needed value
var resultBool = list.Any(row => row["MyColumn"].Equals(searchValue)); // checks, if any DataRows containing needed value exists


If you should make this search often, I think it's not convenient to write LINQ-expression each time. I'd write extension-method like this:

private static bool ContainsValue(this List<DataRow> list, object value)
{
    return list.Any(dataRow => dataRow["MyColumn"].Equals(value));
}

And after that make search:

if (list.ContainsValue("Value"))


http://dotnetperls.com/list-find-methods has something about exists & find.


Well, it depends on what version C# and .NET you are on, for 3.5 you could do it with LINQ:

var qualiyfyingRows = 
   from row in rows
   where Equals(row["MyColumn"], value)
   select row;

// We can see if we found any at all through.
bool valueFound = qualifyingRows.FirstOrDefault() != null;

That will give you both the rows that match and a bool that tells you if you found any at all.

However if you don't have LINQ or the extension methods that come with it you will have to search the list "old skool":

DataRow matchingRow = null;
foreach (DataRow row in rows)
{
   if (Equals(row["MyColumn"], value))
   {
      matchingRow = row;
      break;
   }
}

bool valueFound = matchingRow != null;

Which will give you the first row that matches, it can obviously be altered to find all the rows that match, which would make the two examples more or less equal.

The LINQ version has a major difference though, the IEnumerable you get from it is deferred, so the computation will not be done until you actually enumerate it's members. I do not know enough about DataRow or your application to know if this can be a problem or not, but it was a problem in a piece of my code that dealt with NHibernate. Basically I was enumerating a sequence which members where no longer valid.

You can create your own deferred IEnumerables easily through the iterators in C# 2.0 and higher.


I may have misread this but it seems like the data is currently in a List<object[]> and not in a datatable so to get the items that match a certain criteria you could do something like:

var matched = items.Where(objArray => objArray.Contains(value));

items would be your list of object[]:s and matched would be an IEnumerable[]> with the object[]:s with the value in.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜