0

Hi I have a record called Tags in a table called Knowledgebase (KB) in my DB. The words in Tags are separated by commas. Also in the KB table is a field called Title.

I need to match the tags field to the Title so I have replaced all the commas in the tags with spaces like so string removeCommas = commas.Replace(",", " ");.

I think I now need to loop around every record in the KB table to find records? I would like to store the number of matches it finds in a variable called suggestions.

Question is what is the best way to implement the for each loop for a query like this? Is the for each loop the best method for this task?

ASPCoder1450
  • 1,651
  • 4
  • 23
  • 47

3 Answers3

0

One way is to store the space seperated strings in a List. Now, use Foreach loop for the whole table and in turn a foreach loop for each record to find the match of Title.

0

Yes Linq can help you to retreive the data from your database and then replacing it after a foreach loop

Code Added

Let say you are using EDM and you have a context kb:

public void ReplaceCommaInTag(KbContext kb)
 {
    var tags = from t in kb.Titles
               Select t.Tags;

    foreach(Tag tag in tags)
     {
      tag = tag.Replace(","," ");
     }

    try
    {
     kb.SubmitChanges();
    }

    catch(Exception e)
    {
    //Display the error.
    }
}

I hope it will help you

0

I will correct my answer if this is going the wrong direction, but would something like this complete the operation you are attempting?

System.Data.DataTable KB = new System.Data.DataTable();
string[] tags = "some,foo,bar".Split(',');
System.Collections.Generic.List<string> suggestions = new System.Collections.Generic.List<string>();

for (int i = 0; i < tags.Length; i++)
{
    for (int j = 0; j < KB.Rows.Count; j++)
    {
        string row = KB.Rows[j]["Title"].ToString();
        if ((row.Contains(tags[i]))
        {
            suggestions.Add(row);
        }
    }
}

Also, avoid foreach whenever humanly possible. Check out THIS post to see why.

Community
  • 1
  • 1
Volearix
  • 1,573
  • 3
  • 23
  • 49
  • I think its close. The KB table already exists in the underlying context (i'm using ASP.NET MVC) Im bit stuck with how to search the rows in this table (my guess is to use LINQ somehow). – ASPCoder1450 Mar 21 '14 at 20:00
  • Did you read the answers in the question you linked? While a ´´for´´ loop usually is more efficient a ´´foreach´´ loop is much more expressive. It's also lazy which in some situations allows for a lot of optimizations. – Zache Mar 24 '14 at 07:27