score:0
Something like this query will work, but I would recommend putting your values into a different data structure than a string. Possibly a struct with the element names so that you can look up multiple values.
string s1 = "a = 32, b = 432, f = 321, gfs = 43, d = 42, k = 4, t = 44";
string s2 = "a = 23, b = 432, f = 321, gfs = 413, d = 42, k = 4242, t = 4314";
string s3 = "a = 23, b = 21, f = 321, gfs = 413, d = 42, k = 4242, t = 4314";
var array = new string[] { s1, s2, s3 };
var result = array.Where(s => s.Contains("f = 321") && s.Contains("b = 432"));
score:1
if you know that your values are unique, I would construct a hash table where the left hand side of the equal is your key and the right is your value. this will help you avoiding any string formation that might change, for example extra spaces etc.
here is some code sample
static void Main(string[] args)
{
string str = "a = 23, b = 432, f = 321, gfs = 413, d = 42, k = 4242, t = 4314";
Dictionary<string,string> dictionary = ConstructDictionary(str);
// Now you can find what you want in your dictionary
}
private static Dictionary<string,string> ConstructDictionary(string str)
{
string[] pairs = str.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); // this will give you all the pairs X = Y
Dictionary<string, string> dictionary = new Dictionary<string, string>();
foreach (string pair in pairs)
{
string[] keyValue = pair.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries); // this will create an array of size 2 where
array[0] = key and array[1] = value;
string key = keyValue[0].Trim();
string value = keyValue[1].Trim();
if (!dictionary.ContainsKey(key))
{
dictionary.Add(key, value);
}
}
return dictionary;
}
score:1
Here is one way of doing it using an auxiliary function:
private static bool HasAll(string s, string[] keys, int[] vals) {
if (keys.Length != vals.Length) throw new ArgumentException("vals");
var tt = s.Split(new[] {' ', ',', '='});
for(var i = 0 ; i != keys.Length ; i++) {
var pos = Array.IndexOf(tt, keys[i]));
if (pos < 0 || pos == vals.Length-1 || !tt[i+1].Equals(vals[i].ToString())) {
return false;
}
}
return true;
}
Now you can use LINQ to get the items like this:
var keys = new[] {"a", "b", "d", "k"};
var vals = new[] {3, 2, 31, 1};
var res = data.Where(str => HasAll(str, keys, vals)).ToList();
score:1
If I understand the quesiton correctly, this should do it
1) Create a dictionary where the key is the full string and the value is the split pieces of the string
2) Check for intersection of the criteria with the pieces. Intersection size is same as criteria size and we have a match.
[TestMethod]
public void FindValuesInStrings() {
var strings = new[] {
"a = 23, b = 432, f = 321, gfs = 11, d = 42, k = 4242, t = 4314", //A
"a = 12, b = 123, f = 456, gfs = 11, d = 42, k = 4242, t = 4314", //B
"a = 11, b = 456, f = 789, gfs = 413, d = 42, k = 4242, t = 4314", //C
"a = 23, b = 789, f = 12, gfs = 13, d = 42, k = 4242, t = 4314", //D
};
var dict = new Dictionary<string, IEnumerable<string>>();
foreach (var str in strings) {
dict.Add(str, str.Split(',').Select(s => s.Trim()));
}
// finds the two entries where a = 23 (A & D)
var criteria = new[] { "a = 23" };
var found = dict.Where(entry =>
entry.Value.Intersect(criteria).Count() == criteria.Count()).Select(entry => entry.Key);
Assert.AreEqual(2, found.Count());
// finds the single entry where a = 23 and gfs = 11 (A)
criteria = new[] { "a = 23", "gfs = 11" };
found = dict.Where(entry =>
entry.Value.Intersect(criteria).Count() == criteria.Count()).Select(entry => entry.Key);
Assert.AreEqual(1, found.Count());
}
Source: stackoverflow.com
Related Query
- Searching in string collection
- List or Array of String Contain specific word in Html Source Code
- C# - code to order by a property using the property name as a string
- Fastest way to search in a string collection
- Collection to string using linq
- This code returns distinct values. However, what I want is to return a strongly typed collection as opposed to an anonymous type
- LINQ WHERE method alters source collection
- best way to convert collection to string
- convert int to string in linq for searching
- using LINQ how can i concatenate string properties from itesm in a collection
- .NET String parsing performance improvement - Possible Code Smell
- LINQ: Searching a collection within a collection for a single object
- LINQ Source Code Available
- Efficient way to unindent lines of code stored in a string
- NHibernate querying on a string collection using Linq results in either error or empty collection
- Searching in text files for a keyword until a string is encountered
- LINQ to EF - Find records where string property of a child collection at least partially matches all records in a list of strings
- Searching for dictionary keys contained in a string array
- C# Code Contracts -- How to ensure that a collection of items contains items with unique properties?
- .NET 4 Code Contracts: "requires unproven: source != null"
- Searching in text files until specific string
- The given value of type String from the data source cannot be converted to type int of the specified target column
- How can I build a string from a collection with Linq?
- Using LINQ, how can I filter a collection on partial string property?
- Separate a string into a list where is not in a collection Dictionary
- How can I call ToLower() on each string in a collection using LINQ?
- creating Linq to sqlite dbml from DbLinq source code
- Searching by fragments if values are string type but search by and entire if value is int
- Entity Framework Code First String Comparison with Oracle Db
- C#: projection - accessing a given string property in a collection of objects in the same way as a List<string>
More Query from same tag
- how to search Year between in Dynamic Linq
- Mongodb c# Conditions in query LINQ
- Compact way to map an IEnumerable to an ILookup with LINQ
- ToList thows Exception when building Expression tree using concat multiple Expressions
- Linq2Entities Equivalent Query for Parent/Child Relationship, With All Parents and Children, Filtering/Ordering Children
- GroupBy on complex object (e.g. List<T>)
- Pass dynamic data type to function
- Anonymous Methods / Lambda's (Coding Standards)
- Doing a Count in a Linq to SQL Query (created as IQueryable) gets all the rows
- linq query to fetch employee name of those employee who is working on exactly 3 projects
- LINQ - Convert String to Datetime
- INNER JOIN 3 Data Tables using LINQ
- How can I use LINQ to calculate the longest streak?
- C# Linq Ambiguous call Between System.Linq and System.Collections
- Order by in Linq
- LINQ: select certain object properties Into Same object
- format datetime from linq query into selectlist for dropdown
- Linq - Excluding users from list in IQueryable expression - What is the correct way?
- Select distinct values from a list using LINQ in C#
- Output an ordered collection (using LINQ) into a listbox
- Update Database using EF with chunks runs very slowly
- NHibernate LINQ Where and Any throwing exception
- Linq Group by id
- use query linq in search with empty field
- Autocomplete textbox freezes while executing query. Must be a better way!
- check if string contains dictionary Key -> remove key and add value
- Can a generic method return the property I specify
- Filling collection A according to collection B
- Why does joining two related CSV files by using a join clause produce a single element instead of a sequence of elements?
- Linq Select Statement help needed - NullReferenceException after using FirstOrDefault