Check Linq Result for value - c#

How can I check the results of LINQ query for a specific string value?
I have the following linq query:
IEnumerable<DataRow> rows = searchParamsTable.AsEnumerable()
.Where(r => r.Field<String>("TABLE") == tableNumbers[i].ToString()
&& r.Field<String>("FIELD ") == fieldName[i]);
I want to see if the result of that query contains a string(passed in form a text box) "wildcardSearchString".

var searchRows =
rows.Where(tr => tr.ItemArray
.Any(ti => ti.ToString().IndexOf("wildcardSearchString", StringComparison.CurrentCultureIgnoreCase) > 0))
This will go through each of the rows that was returned, and see if "wildcardSearchString" is in the rows item string representation (ignoring case). Here's the problem though, this won't get you wildcard search support, so you'll have to figure that one out yourself. You can try to use Regex, which would require a slight modification:
string searchPattern = "some*string".Replace("*", ".*");
var searchRows =
rows.Where(tr => tr.ItemArray
.Any(ti => Regex.IsMatch(ti.ToString(), searchPattern)))
Hope that helps. Just be warned that if they decide to try supplying a Regex pattern than this might really mess up whatever they were searching for, so you just need to be careful of input.

try with this code
DataRow[] array = rows.ToArray();
array.Contains(yourIndex, yourTextBox.Text);
Add this extension
public static bool Contains(this DataRow[] dataRows, string value, int index)
{
foreach(var row in dataRows)
{
if(row[index].ToString().Contains(value))
{
return true;
}
}
return false;
}

Boolean found = false;
foreach(Datarow d in rows)
{
foreach(object o in d.ItemArray)
{
if(o.ToString().Contains("test")
{
found=true;
break;
}
}
}
Do you mean something like this?

I don't know if you're aware of the built-in search capabilities of a DataTable? You could use its Select method:
DataRow[] rows = searchParamsTable
.Select("TABLE = 'Table1' AND FIELD like '%wildcardSearchString%'");
Linq is OK but not always required :).

Related

Linq Query to check if the records are all the same

I am very much new to the Linq queries. I have the set of records in the csv which is like below
ProdID,Name,Color,Availability
P01,Product1,Red,Yes
P02,Product2,Blue,Yes
P03,Product1,Yellow,No
P01,Product1,Red,Yes
P04,Product1,Black,Yes
I need to check for the Names of the each product and if its is not the same in all the records then I need to send an error message.I know the below query is used to find the duplicates in the records but not sure how can I modify it check if it all has the same values.
ProductsList.GroupBy(p => p.Name).Where(p => p.Count() > 1).SelectMany(x => x);
var first = myObjects.First();
bool allSame = myObjects.All(x=>x.Name == first.Name);
Enumerable.All() will return true if the lambda returns true for all elements of the collection. In this case we're checking that every object's Name property is equal to the first (and thus that they're all equal to each other; the transitive property is great, innit?). You can one-line this by inlining myObjects.First() but this will slow performance as First() will execute once for each object in the collection. You can also theoretically Skip() the first element as we know it's equal to itself.
if I understand correctly you want to check if product exists in the list
using System.Linq;
private bool ItemExists(string nameOfProduct) {
return ProductsList.Any(p=> p.Name== nameOfProduct);
}
UPD after author comment:
To know all the records that are not having the same name as the first record:
var firstName = ProductsList[0].Name;
var differentNames = ProductsList.Where(p => p.Name != firstName);
Another option (just to have all other names): ProductsList.Select(p => p.Name).Where(n => n != firstName).Distinct()
Old version
So, if there are at least two different names then you should return an error?
LINQ way: return ProductsList.Select(p => p.Name).Distinct().Count() <= 1
More optimizied way:
if (ProductsList.Count == 0)
return true;
var name = ProductsList[0].Name;
for (var i = 1; i < ProductsList.Count; i++)
{
if (ProductsList[i].Name != name)
return false;
}
return true;

DataTable select with LiNQ and check is there duplicate rows or not

I used .Net framwork 4.0 with WinForm application component DataGridView and set DataSource with DataTable.Then there's a button to add row into DataGridView.
That code like this.
gridTable = (DataTable)dgrMainGrid.DataSource;
DataRow dr = gridTable.NewRow();
Before adding New Row into DataTable I checked if there's a duplicate row.To do that I used this LINQ Query.
//Item Code cannot duplicate
var results = from itmCode in gridTable.AsEnumerable()
where (itmCode.Field<string>("Item Code") == txtGrdItmLoc.Text)
select itmCode;
There after how I check the duplicate rows available or not in the data table?
if(//doWhatever function here ){
//if there's duplicate row values
isNotDuplicate = false;
}
else{
isNotDuplicate=true;
}
Before go to following step I need to get is there a duplicate or not and set it into isNotDuplicate variable or similar thing to check that. so i think to count the results rows but there's no such function to count 'var results`, Any possibility to do that?
if (!isDuplicate)
{
dr["#"] = true;
dr["Item Code"] = lSysItemCode;
dr["Stock Code"] = txtGdrItmItemLoc.Text;
dr["Brand"] = txtGrdItmBrand.Text;
dr["Model No"] = cmbGrdItmModel.SelectedValue.ToString();
gridTable.Rows.Add(dr);
dgrMainGrid.DataSource = gridTable;
}
I can use for loop with DataTable and check whether it's contain new value that equals to "Item Code" but I looking alternative method with linq.
Simply I'm looking replacement for this by using linq.
foreach (DataRow r in gridTable.Rows) {
if (r["Item Code"].ToString() == txtGrdItmLoc.Text) {
isDuplicate = true;
}
}
Sample Project : http://1drv.ms/1K4JnHt
Sample Code : http://pastebin.com/v7NMdUrf
You have not made it clear that in your DataTable if you are looking for duplicates for any specific Item Code or for any Item Code. Anyways,here is the code for both the scenarios:-
If you are looking for duplicates for any specific Item Code then you can simply check the count like this:-
bool istxtGrdItmLocDuplicate = gridTable.AsEnumerable()
.Count(x => x.Field<string>("ItemCode") == txtGrdItmLoc.Text) > 1;
If you are looking for duplicates in the entire DataTable, then simply group by Item Code and check the respective count for each Item Code like this:-
bool isDuplicate = gridTable.AsEnumerable()
.GroupBy(x => x.Field<string>("ItemCode")
.Any(x => x.Count() > 1);
IEnumerable<T> has a Count() method (check here), if you are not seeing it in intellisense then you are missing some using instruction, like using System.Linq; or some other...
Then you would just do:
if(results.Count()>0){
//if there's duplicate row values
isNotDuplicate = false;
}
else
{
isNotDuplicate=true;
}
First cast it to IEnumerable :
Convert DataRowCollection to IEnumerable<T>
Then you can use LINQ extension methods to do something like this (to check all values that has duplicates):
var duplicates = resultsList.Where(r => resultsList.Count(r2 => r2.Field<string>("Item Code") == r.Field<string>("Item Code")) > 0);
If you want check each value for duplicate you can use .Count method, something like this:
bool hasDuplicates = resultsList.Count(r2 => r2.Field<string>("Item Code") == "your code") > 1;
Ok, if for some reason this doesn't work you can write this function yourself:
public static class Helper
{
// or other collection type
public static int MyCount<T>(this IEnumerable<T> collection, Func<T, bool> function)
{
int count = 0;
foreach (T i in collection)
if (function(i)) ++count;
return count;
}
}
And use it like :
results.MyCount(r => r.Field<string>("Item Code") == "Item Code");

Check if value exists in dataTable?

I have DataTable with two columns Author and Bookname.
I want to check if the given string value Author already exists in the DataTable. Is there some built in method to check it, like for Arrays array.contains?
You can use LINQ-to-DataSet with Enumerable.Any:
String author = "John Grisham";
bool contains = tbl.AsEnumerable().Any(row => author == row.Field<String>("Author"));
Another approach is to use DataTable.Select:
DataRow[] foundAuthors = tbl.Select("Author = '" + searchAuthor + "'");
if(foundAuthors.Length != 0)
{
// do something...
}
Q: what if we do not know the columns Headers and we want to find if any
cell value PEPSI exist in any rows'c columns? I can loop it all to
find out but is there a better way? –
Yes, you can use this query:
DataColumn[] columns = tbl.Columns.Cast<DataColumn>().ToArray();
bool anyFieldContainsPepsi = tbl.AsEnumerable()
.Any(row => columns.Any(col => row[col].ToString() == "PEPSI"));
You can use Linq. Something like:
bool exists = dt.AsEnumerable().Where(c => c.Field<string>("Author").Equals("your lookup value")).Count() > 0;
DataRow rw = table.AsEnumerable().FirstOrDefault(tt => tt.Field<string>("Author") == "Name");
if (rw != null)
{
// row exists
}
add to your using clause :
using System.Linq;
and add :
System.Data.DataSetExtensions
to references.
You should be able to use the DataTable.Select() method. You can us it like this.
if(myDataTable.Select("Author = '" + AuthorName.Replace("'","''") + '").Length > 0)
...
The Select() funciton returns an array of DataRows for the results matching the where statement.
you could set the database as IEnumberable and use linq to check if the values exist.
check out this link
LINQ Query on Datatable to check if record exists
the example given is
var dataRowQuery= myDataTable.AsEnumerable().Where(row => ...
you could supplement where with any

Getting a cell from DataTable.Row.ItemArray with Linq

I have the following ItemArray:
dt.Rows[0].ItemArray.. //{0,1,2,3,4,5}
the headers are : item0,item1,item2 etc..
So far, to get a value from the ItemArray I used to call it by an index.
Is there any way to get the value within the ItemArray with a Linq expression based on the column name?
Thanks
You can also use the column-name to get the field value:
int item1 = row.Field<int>("Item1");
DataRow.Item Property(String)
DataRow.Field Method: Provides strongly-typed access
You could also use LINQ-to-DataSet:
int[] allItems = (from row in dt.AsEnumerable()
select row.Field<int>("Item1")).ToArray();
or in method syntax:
int[] allItems = dt.AsEnumerable().Select(r => r.Field<int>("Item1")).ToArray();
If you use the Item indexer rather than ItemArray, you can access items by column name, regardless of whether you use LINQ or not.
dt.Rows[0]["Column Name"]
Tim Schmelter's answer is probably what you are lookin for, just to add also this way using Convert class instead of DataRow.Field:
var q = (from row in dataTable.AsEnumerable() select Convert.ToInt16(row["COLUMN1"])).ToArray();
Here's what I've come up with today solving a similar problem. In my case:
(1)I needed to xtract the values from columns named Item1, Item2, ... of bool type.
(2) I needed to xtract the ordinal number of that ItemN that had a true value.
var itemValues = dataTable.Select().Select(
r => r.ItemArray.Where((c, i) =>
dataTable.Columns[i].ColumnName.StartsWith("Item") && c is bool)
.Select((v, i) => new { Index = i + 1, Value = v.ToString().ToBoolean() }))
.ToList();
if (itemValues.Any())
{
//int[] of indices for true values
var trueIndexArray = itemValues.First().Where(v => v.Value == true)
.Select(v => v.Index).ToArray();
}
forgot an essential part: I have a .ToBoolean() helper extension method to parse object values:
public static bool ToBoolean(this string s)
{
if (bool.TryParse(s, out bool result))
{
return result;
}
return false;
}

c# finding matching words in table column using Linq2Sql

I am trying to use Linq2Sql to return all rows that contain values from a list of strings. The linq2sql class object has a string property that contains words separated by spaces.
public class MyObject
{
public string MyProperty { get; set; }
}
Example MyProperty values are:
MyObject1.MyProperty = "text1 text2 text3 text4"
MyObject2.MyProperty = "text2"
For example, using a string collection, I pass the below list
var list = new List<>() { "text2", "text4" }
This would return both items in my example above as they both contain "text2" value.
I attempted the following using the below code however, because of my extension method the Linq2Sql cannot be evaluated.
public static IQueryable<MyObject> WithProperty(this IQueryable<MyProperty> qry,
IList<string> p)
{
return from t in qry
where t.MyProperty.Contains(p, ' ')
select t;
}
I also wrote an extension method
public static bool Contains(this string str, IList<string> list, char seperator)
{
if (str == null) return false;
if (list == null) return true;
var splitStr = str.Split(new char[] { seperator },
StringSplitOptions.RemoveEmptyEntries);
bool retval = false;
int matches = 0;
foreach (string s in splitStr)
{
foreach (string l in list)
{
if (String.Compare(s, l, true) == 0)
{
retval = true;
matches++;
}
}
}
return retval && (splitStr.Length > 0) && (list.Count == matches);
}
Any help or ideas on how I could achieve this?
Youre on the right track. The first parameter of your extension method WithProperty has to be of the type IQueryable<MyObject>, not IQueryable<MyProperty>.
Anyways you dont need an extension method for the IQueryable. Just use your Contains method in a lambda for filtering. This should work:
List<string> searchStrs = new List<string>() { "text2", "text4" }
IEnumerable<MyObject> myFilteredObjects = dataContext.MyObjects
.Where(myObj => myObj.MyProperty.Contains(searchStrs, ' '));
Update:
The above code snippet does not work. This is because the Contains method can not be converted into a SQL statement. I thought a while about the problem, and came to a solution by thinking about 'how would I do that in SQL?': You could do it by querying for each single keyword, and unioning all results together. Sadly the deferred execution of Linq-to-SQL prevents from doing that all in one query. So I came up with this compromise of a compromise. It queries for every single keyword. That can be one of the following:
equal to the string
in between two seperators
at the start of the string and followed by a seperator
or at the end of the string and headed by a seperator
This spans a valid expression tree and is translatable into SQL via Linq-to-SQL. After the query I dont defer the execution by immediatelly fetch the data and store it in a list. All lists are unioned afterwards.
public static IEnumerable<MyObject> ContainsOneOfTheseKeywords(
this IQueryable<MyObject> qry, List<string> keywords, char sep)
{
List<List<MyObject>> parts = new List<List<MyObject>>();
foreach (string keyw in keywords)
parts.Add((
from obj in qry
where obj.MyProperty == keyw ||
obj.MyProperty.IndexOf(sep + keyw + sep) != -1 ||
obj.MyProperty.IndexOf(keyw + sep) >= 0 ||
obj.MyProperty.IndexOf(sep + keyw) ==
obj.MyProperty.Length - keyw.Length - 1
select obj).ToList());
IEnumerable<MyObject> union = null;
bool first = true;
foreach (List<MyObject> part in parts)
{
if (first)
{
union = part;
first = false;
}
else
union = union.Union(part);
}
return union.ToList();
}
And use it:
List<string> searchStrs = new List<string>() { "text2", "text4" };
IEnumerable<MyObject> myFilteredObjects = dataContext.MyObjects
.ContainsOneOfTheseKeywords(searchStrs, ' ');
That solution is really everything else than elegant. For 10 keywords, I have to query the db 10 times and every time catch the data and store it in memory. This is wasting memory and has a bad performance. I just wanted to demonstrate that it is possible in Linq (maybe it can be optimized here or there, but I think it wont get perfect).
I would strongly recommend to swap the logic of that function into a stored procedure of your database server. One single query, optimized by the database server, and no waste of memory.
Another alternative would be to rethink your database design. If you want to query contents of one field (you are treating this field like an array of keywords, seperated by spaces), you may simply have chosen an inappropriate database design. You would rather want to create a new table with a foreign key to your table. The new table has then exactly one keyword. The queries would be much simpler, faster and more understandable.
I haven't tried, but if I remember correctly, this should work:
from t in ctx.Table
where list.Any(x => t.MyProperty.Contains(x))
select t
you can replace Any() with All() if you want all strings in list to match
EDIT:
To clarify what I was trying to do with this, here is a similar query written without linq, to explain the use of All and Any
where list.Any(x => t.MyProperty.Contains(x))
Translates to:
where t.MyProperty.Contains(list[0]) || t.MyProperty.Contains(list[1]) ||
t.MyProperty.Contains(list[n])
And
where list.Any(x => t.MyProperty.Contains(x))
Translates to:
where t.MyProperty.Contains(list[0]) && t.MyProperty.Contains(list[1]) &&
t.MyProperty.Contains(list[n])

Categories