Manek
Manek

Reputation: 568

List Collection Contains exact string

I have a List Collection and say that i am adding 3 items to them.

list.Add(new ContentDomain() {  Id = "1" , Content = "aaa,bbb,ccc,ddd"});
list.Add(new ContentDomain() {  Id = "2" , Content = "aa,bb,cc,dd"});
list.Add(new ContentDomain() {  Id = "3" , Content = "a,b,c,d"});

Now what i want is to fetch the rows that have just 'a' in the Content attribute.

Like i tried something like

list = list.Where(x => x.Content.ToLower().Contains("a")).ToList();

but that would give me all the three rows.

i want to search in a string for the exact string only.

Upvotes: 3

Views: 4365

Answers (3)

Peter
Peter

Reputation: 27944

list.Where(x => x.ToString().ToLower().Split(',').Where(a => a.Trim() == "a").Any()).ToList();

edit: Changed Count() > 0 to Any() for better performance

Upvotes: 8

Azhar Khorasany
Azhar Khorasany

Reputation: 2709

Try this:

        IList<ContentDomain> returned = new List<ContentDomain>();
        foreach(ContentDomain myList in list)
        {
            var ret = myList.Content.Split(',');
            bool exists = (from val in ret
                          where val.Contains('a')
                          select true).FirstOrDefault();
            if (exists)
                returned.Add(myList);
        }

Upvotes: 0

Thinhbk
Thinhbk

Reputation: 2214

Convert it to an array of strings, and find the string in the array.

list = list.Where(x => x.Content.ToLower().Split(',').IndexOf("a")>= 0).ToList();

Upvotes: 0

Related Questions