Home > database >  C# linq split ,order by and join the value
C# linq split ,order by and join the value

Time:06-21

I Have below code . it working as I am excepting. but I want to reduce the number of line code. In the foreach loop i am doing split ,order by and join the value. so other way we can write it ?

class a
{
 public string Test { get; set; }
 public string Code { get; set; }
}

var masterFormList = "BBB,AAA,CCC,FFF,GGG,HHH";
List<a> mData = new List<a>();
 
mData.Add(new a { Test = "AAA,BBB,CCC,FFF,GGG,HHH", Code = "A" });
mData.Add(new a { Test = "BBB", Code = "B" });
mData.Add(new a { Test = "CCC", Code = "C" });
mData.Add(new a { Test = "FFF", Code = "D" });
mData.Add(new a { Test = "GGG", Code = "E" });
mData.Add(new a { Test = "HHH", Code = "F" });
var masterSet = masterFormList.Split(',').OrderBy(y => y);
var l = string.Join(",", masterSet);
    
    
string value = "";
foreach (var item in mData)
{
   var listSplite = item.Test.Split(',').OrderBy(y => y);
     if (l == string.Join(",", listSplite))
     {
     value = item.Code;
    
      }
  }

CodePudding user response:

As I see you want to find elements that have given list of codes in Test property. For that I'd write help method and use LINQ methods as below:

var masterFormList = "BBB,AAA,CCC,FFF,GGG,HHH";

List<ExampleClass> mData = new List<ExampleClass>();

mData.Add(new ExampleClass { Test = "AAA,BBB,CCC,FFF,GGG,HHH", Code = "A" });
mData.Add(new ExampleClass { Test = "BBB", Code = "B" });
mData.Add(new ExampleClass { Test = "CCC", Code = "C" });
mData.Add(new ExampleClass { Test = "FFF", Code = "D" });
mData.Add(new ExampleClass { Test = "GGG", Code = "E" });
mData.Add(new ExampleClass { Test = "HHH", Code = "F" });

// You can use here also Where method that will return list of items
var masterItem = mData.FirstOrDefault(x => AreListsEquivalent(masterFormList, x.Test));

Console.ReadKey();

// Helper method to compare list in form of comma separated values.
static bool AreListsEquivalent(string list1, string list2)
{

    return list1.Split(',').ToHashSet()
        .SetEquals(list2.Split(',').ToHashSet());
}

// Test class
public class ExampleClass
{
    public string Test { get; set; }
    public string Code { get; set; }
}

enter image description here

CodePudding user response:

I think you can just do your string comparisons, but be a bit more abbreviated by using LINQ:

var masterKey = String.Join(",", masterFormList.Split(',').OrderBy(y => y));

var value = mData.Where(a => masterKey == String.Join(",", a.Test.Split(',').OrderBy(y => y)))
                 .LastOrDefault()
                 ?.Code;
  • Related