简体   繁体   中英

Linq to SQL compare two comma delimited strings

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;

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));

You can try:

  1. Splitting the first string and the second string by a comma.
  2. 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); 

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.

Try this way

string string2 = "G,L";
var result = from item in oTable
             where string2.All(x => item.string1.Contains(x))
             select item;

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.

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");
        }

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM