2

I have a list of string like this

List<string> list1 = new List<string>();

For example my list is

{one , two , three , four , five}

In database I have a string like this

"five-six-seven-eight"

How I can use Linq to SQL to search between my string in database and my list. For example my query search should be true because "five" is common on both. My query is this:

var q = from p in m.ViewAbuseReports where
 (list1.Contains(p.Abuse.ToString().Split('-')) || list1.Count == 0)
    select new
    {
        Col2 = p.FirstName + " " + p.LastName,
        Col3 = p.DateTakhalof,
        Col4 = p.DateReturn
    };
5
  • I didn't get the question, would you kindly clarrify some more. Commented Feb 18, 2016 at 7:56
  • 1
    Seems like you need LINQ Intersect Commented Feb 18, 2016 at 7:57
  • @Ovis I want to search a list of string in a string , My string in database splitted with "-" Commented Feb 18, 2016 at 7:59
  • @Ian would you please give me some example ? Commented Feb 18, 2016 at 7:59
  • @mosyflasher example added. Let me know if that fits what you need. Commented Feb 18, 2016 at 8:01

2 Answers 2

3

You may consider using LINQ Intersect.

var q = from p in m.ViewAbuseReports
 let ps = p.Abuse.ToString().Split('-')
 let i = list1.Intersect(ps).ToList() //here you get if there is any intersect (common elements) between the two `IEnumerable`
 where (i.Count > 0 || list1.Count == 0)
 select new
 {
    Col2 = p.FirstName + " " + p.LastName,
    Col3 = p.DateTakhalof,
    Col4 = p.DateReturn
 };
Sign up to request clarification or add additional context in comments.

4 Comments

Intersect will not work with local collection in LinQToSQL.
@mosyflasher great! Glad that my solution fits your need. ;)
But we should consider that use .AsEnumerable() to work
@mosyflasher use .AsEnumberable()? @.@?
2
var q = from p in m.ViewAbuseReports where
(list1.Any(l => p.Abuse.ToString().Contains(l)) || list1.Count == 0)
select new
{
    Col2 = p.FirstName + " " + p.LastName,
    Col3 = p.DateTakhalof,
    Col4 = p.DateReturn
};

If any of the strings in list1 is in p.Abuse this will be true. This way you don't have to take care of splitting the string (which would be a hard thing to do in database).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.