I have a List
of Results
. My goal is to extract the Result
property Method
from all elements of List<Result>
, make extracted elements unique and prepare a string for SQL statements like WHERE method IN ('A','B','C')
.
Here is the Result
class and a List<Result>
example. The solution is in the ListTransformation()
method.
Result.cs
public class Result
{
public int Id { get; set; }
public string Method { get; set; }
}
Program.cs
A method value can be one method ("A"
) or more methods separated by a colon ("A:B:C"
).
static void ListTransformationTest()
{
const string separator = ":";
List<Result> results = new List<Result>
{ new Result { Id = 1, Method = null },
new Result { Id = 1, Method = "" },
new Result { Id = 2, Method = "A:B" },
new Result { Id = 3, Method = "B:C" },
new Result { Id = 4, Method = "A:C:B" }
};
string methods = string.Join(separator,
results.Where(x => x.Method?.Length > 0)
.Select(r => r.Method).ToArray());
var uniqueMethods = methods.Split(separator[0]).Distinct();
string uniqueMethodsSqlFormat =
string.Join(",", uniqueMethods.Select(m => string.Format($"'{m}'")).ToArray());
}
I guess there are a lot of operations. Do you have any suggestions on improving the code or any alternative code?