Contains in lambda expression [Resolved]

Posted by Venkatesh under LINQ on 3/24/2016 | Points: 10 | Views : 306 | Status : [Member] | Replies : 2
Hi,

I have variable like string str="ABCD";
I have list object which contains some columns like ID,Username. In this object username getting with separated comma.
I want get the list of ID's of "ABCD" username?

How can i get this with lambda expression?

Thanks,
Venkatesh.P




Responses

Posted by: Rajnilari2015 on: 3/24/2016 [Member] [Microsoft_MVP] [MVP] Platinum | Points: 50

Up
0
Down

Resolved
@Venkatesh,
Try this

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
List<Test> objTest = new List<Test>();
objTest.Add(new Test { ID = 1, UserName = "ABCD,EF,A,B,C" });
objTest.Add(new Test { ID = 2, UserName = "KK,LL,QA,AQB,RC" });
objTest.Add(new Test { ID = 3, UserName = "UTI" });
objTest.Add(new Test { ID = 4, UserName = "EOF,UB,ABCD,C" });

string str = "ABCD";
string[] stringSeparator = new string[] { "," };

objTest
.ForEach(i =>
{
if (i.UserName
.Split(stringSeparator, StringSplitOptions.None)
.Any(j => j.StartsWith(str)))
{
Console.WriteLine("The search string {0} is present in {1} where the ID is {2}", str, i.UserName, i.ID);
}
});
Console.ReadKey();
}
}

public class Test
{
public int ID { get; set; }
public string UserName { get; set; }
}
}


Result

The search string ABCD is present in ABCD,EF,A,B,C where the ID is 1
The search string ABCD is present in EOF,UB,ABCD,C where the ID is 4


Hope this helps

--
Thanks & Regards,
RNA Team

Venkatesh, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Sheonarayan on: 3/24/2016 [Administrator] HonoraryPlatinum | Points: 25

Up
0
Down
You can use .Contains method of LINQ.

var result = list.Where(d => d.UserName.Contains("ABCD"));
and you should get desired result.

Like contains you have StartsWith, EndsWith methods also, you can use them as well to these scenarios. To know more about LINQ methods, I would highly recommend you to read this post of mine http://www.dotnetfunda.com/articles/show/993/frequently-used-linq-extension-methods.

Thanks and hope this helps.

Regards,
Sheo Narayan
http://www.dotnetfunda.com

Venkatesh, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response