-3

I'm working in List and storing my data in class and again using new list to differentiate between receive data.

I'm using startswith function to check for data inside a string. But i also want to call startswith function inside loop with string is data form class. I can't add startwith because my class don't have definition for this function

Below is demo code help you understand what i'm asking

 class URLClass
{
    public URLClass()
    {

    }

    //packet count
    private int pktCount;
    public int PktCount
    {
        get { return pktCount; }
        set { pktCount = value; }
    }

    //URL accessed
    private string uRLString;
    public string URLString
    {
        get { return uRLString; }
        set { uRLString = value; }
    }}

This is a class data... I used a list for class data and name it URLData

Below code is the loop

foreach (var x in URLData) //URLData is list from above class
{
  if (x.StartsWith("SomeText")) // Here i face problem my class don't have any definition of Sartswith function is there any way i can define it manually
}
zx485
  • 28,498
  • 28
  • 50
  • 59

2 Answers2

1

If you can't modify your URLClass to add the StartsWith method, you can still provide an extension method which may be equally useful.

public static class MyURLClassExtensions {
    public static bool StartsWith(this URLClass me, string text) {
        return me.URLString.StartsWith(text);
    }
}
Wyck
  • 10,311
  • 6
  • 39
  • 60
0

Add the method to the class:

class URLClass
{
    public URLClass()
    {

    }

    //packet count
    private int pktCount;
    public int PktCount
    {
        get { return pktCount; }
        set { pktCount = value; }
    }

    //URL accessed
    private string uRLString;
    public string URLString
    {
        get { return uRLString; }
        set { uRLString = value; }
    }}

    public bool StartsWith(string match)
    {
        return uRLString.StartsWith(match);
    }

OR

Use the string property in the loop:

foreach (var x in URLData) 
{
    if (x.URLString.StartsWith("SomeText"))
}

Either should work, and it's all pretty basic 101-level stuff.

You can also do this:

foreach (var x in URLData.Where(u => u.URLString.StartsWith("SomeText")))
{

}
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794