Reputation: 13
I am using Linq to SQL and I have two comma delimited strings.
string1
is from a database table and looks like "Y,J,A,F,L,R,G".
string2
is obtained from an object and looks like "G,L".
What I am struggling with is to check that the contents of string2
are in string1
.
This is what i currently have:
var result = from d in oTable
where d.string1.Contains(string2)
select d;
Upvotes: 0
Views: 2451
Reputation: 1138
Try this way
string string2 = "G,L";
var result = from item in oTable
where string2.All(x => item.string1.Contains(x))
select item;
Upvotes: 1
Reputation: 13
Thanks to @SonerGönül the below worked.
var result = "G,L".All(c => "Y,J,A,F,L,R,G".Contains(c));
Though i agree with everyone else, this is not how the data should be stored and I'll be passing that onto my client.
Upvotes: 1
Reputation: 19169
You can use Union and Distinct.
var containts = string2.Union(string1).Count() == string1.Distinct().Count();
If Union changes the length of string1.Distinct()
it means there was something else in string2 that was not in string1. If the length does not change (==
) then it means every thing in string2 was also inside string1.
Upvotes: 0
Reputation: 4630
You Can Use, Intersect
See Demo Here
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
string str="Y,J,A,F,L,R,G";
string[] arr=str.Split(',');
string[] x=new String[2]{"G","r"};
IEnumerable<String> x1=arr.Intersect(x);
if(x1.Any())
{
foreach(string st in x1)
{
Console.WriteLine("Matched String: "+st);
}
}
else
{
Console.WriteLine("Empty Matching");
}
}
}
Upvotes: 0
Reputation: 139
You can try:
Then using LINQ Except (MSDN reference) to check if all substrings of string2 are contained in string1
string string1 = "Y,J,A,F,L,R,G";
string string2 = "B,L";
string[] elementsString1 = string1.Split(',');
string[] elementsString2 = string2.Split(',');
bool contained = !elementsString2.Except(elementsString1).Any();
Console.WriteLine(contained);
Upvotes: 1
Reputation: 5072
So you can look in All
or Any
methods, or use Select
to get result for each char.
string first = "Y,J,A,F,L,R,G";
string second = "G,L,X";
// result for each in "second"
IEnumerable<bool> contains = second.Split(',').Select(res => first.Contains(res));
// true if all are contained in first
bool all = second.Split(',').All(res => first.Contains(res));
// true if any is contained in first
bool any = second.Split(',').Any(res => first.Contains(res));
Upvotes: 2