Using the .net Framework 4.8 I'm trying to write an some Linq where the Where clause contains items meeting certain criteria - but excludes a subset of those items meeting some other conditions. Here's a summary of the situation and I will provide full sample code below:
I have a list of objects where 2 properties are:
ParmDir (string: i.e. IN, OUT, INOUT)
ParmName (string: i.e. @Id, @Parm1, @ErrorLogId, @OutParm1, @OutParm2, etc....)
1) I want to filter the list where ParmDir contians "IN" or "INOUT".
2) Of those, I want to exclude any items where the ParmName contains "@ErrorLogId".
I have step one working:
var including = new string[] { "OUT", "INOUT" };
outPutCount = list.Where(x => including.Contains(x.ParmDir)).Count();
But what is the syntax to exclude something like:
var excluding = new string[] { "ErrorLogId" };
x <> excluding.Contains(x.ParmName)
//So the full statement would be something like this:
var including = new string[] { "OUT", "INOUT" };
var excluding = new string[] { "ErrorLogId" };
outPutCount = list.Where(x => including.Contains(x.ParmDir) && x <> excluding.Contains(x.ParmName)).Count();
Thanks.
Here's all the code to test in a console app:
class Program
{
static void Main(string[] args)
{
List<Parm> list = new List<Parm>();
list.Add(new Parm("@Id", "IN", 1, "uniqueidentifier"));
list.Add(new Parm("@Parm1", "IN", 2, "varchar"));
list.Add(new Parm("@Parm2", "IN", 3, "int"));
list.Add(new Parm("@Parm3", "IN", 4, "decimal"));
list.Add(new Parm("@ErrorLogId", "INOUT", 4, "uniqueidentifier"));
list.Add(new Parm("@OutParm1", "OUT", 5, "int"));
list.Add(new Parm("@OutParm2", "INOUT", 6, "varchar"));
list.Add(new Parm("@OutParm3", "INOUT", 7, "decimal"));
list.Add(new Parm("@OutParm4", "INOUT", 8, "int"));
int totalCount = 0;
int outPutCount = 0;
int errorLogCount = 0;
totalCount = (from x in list select x).Count();
var including = new string[] { "OUT", "INOUT" };
var excluding = new string[] { "ErrorLogId" };
outPutCount = list.Where(x => including.Contains(x.ParmDir)).Count();
Console.WriteLine("totalCount = " + totalCount.ToString());
Console.WriteLine("outPutCount = " + outPutCount.ToString());
}
public class Parm
{
string _parmName;
string _parmDir;
int _sort;
string _sQLDataType;
public Parm(string parmName, string parmDir, int sort, string sQLDataType)
{
_parmName = parmName;
_parmDir = parmDir;
_sort = sort;
_sQLDataType = sQLDataType;
}
public string ParmName { get => _parmName; set => _parmName = value; }
public string ParmDir { get => _parmDir; set => _parmDir = value; }
public int Sort { get => _sort; set => _sort = value; }
public string SQLDataType { get => _sQLDataType; set => _sQLDataType = value; }
}
}