Click here to Skip to main content
15,891,248 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
Hello,

How to find a string is already present in a list.For example i have a list that contains data now if i want to write the data in to another list during this i want to keep a condition whether the string is already present in the list.I am using the below code but its not working can you kindly help me

C#
List<list><string>> Messlist
List<string> val= new List<string>();

if (!(Messlist.Contains(val)))
{
---
}
Posted
Updated 31-Mar-15 0:14am
v3

Try LINQ -
C#
var result = Messlist
    .Where(x=> x.Contains(searchString));
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 31-Mar-15 7:34am    
5ed.
—SA
Abhinav S 31-Mar-15 7:42am    
Thank you SA.
Your problem is that val is another List but Contains expects a string

To see if one list contains the values in another use the List<t>.Intersect[^] method and check against the Count Any property

E.g.
C#
private void button1_Click(object sender, EventArgs e)
{
    var l1 = new List<string> {"1", "2", "3", "4", "5", "6"};
    var l2 = new List<string> { "4", "5"};
    var l3 = new List<string> {"7", "8"};

    ListCheck(l1, l2);
    ListCheck(l1, l3);
}

private static bool ListCheck<T>(IEnumerable<T> l1, IEnumerable<T> l2)
{
    // TODO: Null parm checks
    if (l1.Intersect(l2).Any())
    {
        Console.WriteLine("matched");
        return true;
    }
    else
    {
        Console.WriteLine("not matched");
        return false;
    }
}



Or change val to be a single string
 
Share this answer
 
v2
Comments
King Fisher 31-Mar-15 6:31am    
my 5+.
CHill60 31-Mar-15 6:34am    
Thank you! I've modified my solution to use Any instead of Count ... I need to get with the times ;-)
Sergey Alexandrovich Kryukov 31-Mar-15 7:35am    
5ed.
—SA
CHill60 31-Mar-15 7:47am    
Thank you.
Matt T Heffron 31-Mar-15 13:49pm    
+5
 
Share this answer
 
try the below

List<string> newlist = Messlist.Distinct().ToList();

Thank You,
--RG
 
Share this answer
 
Comments
CHill60 31-Mar-15 7:49am    
How does this determine if an item, or a list of items, is already present in the list?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900