Given a DataView that contains multiple rows, I want to extract a row based on the following criteria;
- If a row starts with a certain string and ends with a certain string, then choose that row above all others
- If no rows meet the first criteria, then just look for a row that start with the certain string
- If we can’t match any of the above, default to null.
My quick attempt simply returns the first row that meets any criteria (excuse me if the VB syntax isn’t right, I’m not that familiar with it);
Dim result = (From row In dv.Table.Rows() _
Where (GetString(row, "id").StartsWith(Me.ID.Substring(0, 3), StringComparison.OrdinalIgnoreCase) AndAlso _
GetString(row, "id").EndsWith(Me.ID.Substring(Me.RegisteredID.Length - 2, 2), StringComparison.OrdinalIgnoreCase)) OrElse _
GetString(row, "id").StartsWith(Me.ID.Substring(0, 3), StringComparison.OrdinalIgnoreCase) _
Select row).FirstOrDefault()
Edit: I meant to add that something like https://stackoverflow.com/a/443055/685760 looks promising, but I don’t think it will work in my situation. Feel free to correct me if I’m wrong.
It would be difficult, if not impossible, to express that kind of algorithm in a query. A query will only judge each row independantly from the others.
You need to have the resultset of the first criteria before you can check for the second…
In my opinion you need to do three separate queries (which might just be ending up executing only the first one if it returns any result, since at that point you met your first criteria and do not need to check for other results).
The other way would be, I guess, through some kind of ranking of the data, but you might end up with something less clear AND less performant.
In any case, your code will be a hundred times more readable for common mortals, even if there was a way to express your needs in a query. There is such a thing as overuse of Linq 😉