-6

I have following code in my project

var ReturnStr = Final_BOM.Tables[0].Rows[0]["NEW_BOM_IDS"].ToString();

the above line returns "12,13" but some times only "12"

var ReturnBOM = dsBOMDEfault.Tables[0].Rows[0]["Item_ID"].ToString();

the above line returns "14,15,13".

I want to check ReturnBOM values in ReturnStr

Can any one help how to check

8
  • So, you want to check what values of ReturnBom are present in ReturnStr? Oct 12, 2017 at 11:20
  • 1
    before ask please read the doc : stackoverflow.com/help/how-to-ask have good working. Oct 12, 2017 at 11:21
  • yes, you are correct
    – bless
    Oct 12, 2017 at 11:21
  • ReturnBOM.Split(',').Any(x => ReturnStr.Split(',').Contains(x))
    – BurnsBA
    Oct 12, 2017 at 11:24
  • or ReturnBOM.Split(',').Intersect(ReturnStr.Split(',')).Count() > 0
    – BurnsBA
    Oct 12, 2017 at 11:25

3 Answers 3

2

You can use intersect:

Here a quick one-liner:

var results = ReturnStr.Split(',').Select(int.Parse)
    .Intersect(ReturnBOM.Split(',').Select(int.Parse))

Demo:

using System;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var ReturnStr = "12,13";
        var ReturnBOM = "14,15,13";

        // Convert string to array with Split(',')
        // if you dont want int just remove `.Select(int.Parse)`
        var ReturnStrElements = ReturnStr.Split(',').Select(int.Parse);
        var ReturnBOMElements = ReturnBOM.Split(',').Select(int.Parse);

        // Keep only common elements
        var results = ReturnStrElements.Intersect(ReturnBOMElements);

        foreach(var item in results)
        {
            Console.WriteLine(item);
        }
    }
}
  • We use Split() to convert a string to an array where the delimiter is ','
  • [Optional] We use Select(int.Parse) to convert each element from string to int.
  • We use Intersect() to keep only common elements
1

Use LINQ.

using System.Linq;

The below code will give you an IEnumerable of String with the values you are looking for.

var inBoth = ReturnStr.Split(',').Intersect(ReturnBOM.Split(','))

You may then iterate through the values, cast them to Int32 or do whatever action you want.

1

If i understanded rights:

        string[] returnBomVals = ReturnBom.Split(',');
        string[] returnStrVals = ReturnStr.Split(',');
        foreach (var vals in returnStrVals)
        {
            foreach (var strVals in returnBomVals)
            {
                if (ReturnStr.Equals(vals))
                {
                    //Do Actions
                }
            }
        }
1
  • 2
    if ReturnStr is the following value: "123" and ReturnBom is "12", your code will give a false positive.
    – Kjetil
    Oct 12, 2017 at 11:29

Not the answer you're looking for? Browse other questions tagged or ask your own question.