0
public class abcd
{
    public string sampleA;
    public string sampleB;

    public abcd(string _sampleA, string _sampleB)
    {
        sampleA = _sampleA;
        sampleB = _sampleB;
    }
}

string filter = "Filter";
List<abcd> listA = new List<abcd>();

I am trying to figure out how to write a foreach statement to retrieve all the class instances in my listA that have sampleA contain the string filter.

Basically foreach abcd sampleA in listA that contain filter do this...

Thanks in advance for any help

Nick Udell
  • 2,420
  • 5
  • 44
  • 83
teepee
  • 309
  • 3
  • 5
  • 13

1 Answers1

4
foreach(abcd obj in listA.Where(a => a.sampleA.Contains("Filter")))
{
    // ...
}

if you want to compare case-insensitive:

foreach (abcd obj in listA
    .Where(a => a.sampleA.IndexOf("Filter", StringComparison.CurrentCultureIgnoreCase) >= 0))
{
    // ...
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • Should the LINQ expression take place before the foreach so that it isn't executed every iteration? – Nick Udell May 15 '14 at 15:27
  • 1
    @NickUdell Now also [it won't be executed in every iteration](http://stackoverflow.com/questions/19867012/does-foreach-evaluate-the-array-at-every-iteration/19867119#19867119) – Sriram Sakthivel May 15 '14 at 15:28