在 IF 语句 C# 中对多个条件进行分组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10182834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 12:46:58  来源:igfitidea点击:

Grouping multiple conditions in IF statements C#

c#if-statementconditional-statements

提问by a d

I'm writing a program that needs to perform a search as one of the required functions. The user should be able to use any number of fields, ranging from none to all of them (total of 7). So far I've had success grouping each case of data input within an if statement like so:

我正在编写一个程序,需要执行搜索作为必需的功能之一。用户应该能够使用任意数量的字段,范围从无到所有(总共 7 个)。到目前为止,我已经成功地将每个数据输入案例分组到 if 语句中,如下所示:

List<TypeClass> myList = new List<TypeClass>

foreach TypeClass currentItem in myList

{
    if (data1 == currentItem.GetData1() || data1 == "Do Not Search" && (data2 == currentItem.GetData2() || data2 == "Do Not Search") && (data3...)

    {
        //Stuff
    }

}

If you notice, I grouped each data field within brackets, so the statement can only be satisfied if each of the entered data is either the needed condition, or an 'empty field'. However, I can't group the very first portion of the statement as I do with the other data2,3,4... Instead the statement always gets evaluated to true even if there are other search fields that do not satisfy the conditions of the statement. If I use additional brackets the program completely ignores the if statement and treats it as if none of the cases match at all.

如果您注意到,我将每个数据字段分组在括号内,因此只有输入的每个数据都是所需条件或“空字段”时,才能满足该语句。但是,我无法像处理其他 data2,3,4 那样对语句的第一部分进行分组...相反,即使存在不满足条件的其他搜索字段,该语句也始终被评估为 true该声明。如果我使用额外的括号,程序将完全忽略 if 语句并将其视为没有任何情况匹配。

So if I write it like this:

所以如果我这样写:

if ((data1 == currentIten.GetData1 || data1 == "Do Not Search") && (data2...)

Nothing gets checked and the statement is ignored. Is this normal? Are there any better/more efficient ways of dealing with optional search field selection?

没有检查任何内容并且忽略该语句。这是正常的吗?是否有更好/更有效的方法来处理可选的搜索字段选择?

EDIT: Sorry for the typo, each GetDataX is an accessor and I forgot to write the parentheses ()

编辑:抱歉输入错误,每个 GetDataX 都是一个访问器,我忘了写括号 ()

回答by tsells

You could do it like this for an or condition

你可以在 or 条件下这样做

        List<string> mylist = new List<string>();
        string data1 = "test1";
        string data2 = "test2";
        string data3 = "test3";
        string data4 = "test4";


        foreach (string s in mylist)
        {
            bool found = false;

            if(data1.Equals(s) || data1.Equals("Do not Search"))
            {
                found = true;
            }

            if (data2.Equals(s) || data1.Equals("Do not Search"))
            {
                found = true;
            }

            if (data3.Equals(s) || data1.Equals("Do not Search"))
            {
                found = true;
            }

            if (data4.Equals(s) || data1.Equals("Do not Search"))
            {
                found = true;
            }


        }

Or like this for an and condition

或者像这样一个和条件

        List<string> mylist = new List<string>();
        string data1 = "test1";
        string data2 = "test2";
        string data3 = "test3";
        string data4 = "test4";


        foreach (string s in mylist)
        {
            bool found = false;
            bool notfound = false;

            if(data1.Equals(s) || data1.Equals("Do not Search"))
            {
                found = true;
            }
            else
            {
                notfound = true;
            }

            if (data2.Equals(s) || data1.Equals("Do not Search"))
            {
                found = true;
            }
            else
            {
                notfound = true;
            }
            if (data3.Equals(s) || data1.Equals("Do not Search"))
            {
                found = true;
            }
            else
            {
                notfound = true;
            }
            if (data4.Equals(s) || data1.Equals("Do not Search"))
            {
                found = true;
            }
            else
            {
                notfound = true;
            }

            // Force all to match
            if (notfound)
                return null;
        }

My Preference would be something like this though where you can leverage search functions to do what you need to.....

我的偏好是这样的,尽管您可以利用搜索功能来做您需要做的事情.....

List<string> mylist = new List<string>();

        List<string> mysearches = new List<string>();

        string data1 = "test1";
        string data2 = "test2";
        string data3 = "test3";
        string data4 = "test4";

        if(data1 != "Do not Search")
            mysearches.Add(data1);
        if (data2 != "Do not Search")
            mysearches.Add(data2);
        if (data3 != "Do not Search")
            mysearches.Add(data3);
        if (data4 != "Do not Search")
            mysearches.Add(data4);
        bool found = false;
        bool andconditionmatch = true;

        foreach (string s in mylist)
        {
            if (mysearches.Contains(s))
            {
                found = true;
            }
            else
            {
                andconditionmatch = false;
            }
        }

回答by Sandeep

Put all the possibilities in hashset .

把所有的可能性都放在 hashset 中。

Hashset with all possibilities.

foreach(item in selectedItems) //you may not need this if you dont have to perform action forall selected items.
{
     if (Hashset contains item)
       //do stuff.
}

回答by ja72

I would move the matching inside the class and instead of dealing with 7 separate possible values to match, make them one class instance called criteria. See sample code below:

我会将匹配移到类中,而不是处理 7 个单独的可能值进行匹配,而是将它们设为一个名为criteria. 请参阅下面的示例代码:

public enum States
{
    None,
    Tenesee,
    Georgia,
    Colorado,
    Florida
}
class Item
{
    public States State { get; set; }
    public string Name { get; set; }
    public int ID { get; set; }

    public bool IsMatch(Item criteria)
    {
        bool match = true;
        if (criteria.State != States.None) match &= criteria.State == State;
        if (!string.IsNullOrEmpty(criteria.Name)) match &= criteria.Name.Equals(Name);
        if (criteria.ID > 0) match &= criteria.ID == ID;
        return match;
    }
    public override string ToString()
    {
        return string.Format("ID={0}, Name={1}, State={2}", ID.ToString(), Name, State.ToString());
    }
}
class Program
{

    static void Main(string[] args)
    {

        List<Item> list = new List<Item>();
        list.Add(new Item() { ID = 10016, Name = "Julia", State = States.Georgia });
        list.Add(new Item() { ID = 10017, Name = "Scott", State = States.Colorado });
        list.Add(new Item() { ID = 10018, Name = "Samantha", State = States.Tenesee });
        list.Add(new Item() { ID = 10019, Name = "Julia", State = States.Florida });


        Item criteria = new Item()
        {
            State = States.Tenesee,
            ID = 10018
        };
        List<Item> selection = list.FindAll((item) => item.IsMatch(criteria));

        foreach (var item in selection)
        {
            Console.WriteLine("{0}", item);
        }

    }
}

With the result ID=10018, Name=Samantha, State=Tenesee

结果 ID=10018, Name=Samantha, State=Tenesee

So you build a criteria instance Itemand compare for a match if a property is well defined. The loop through all the items and select the ones that match the criteria. Obviously you have to extend .IsMatch()for all 7 properties.

因此,您构建了一个标准实例Item并比较了一个属性是否定义良好。循环遍历所有项目并选择符合条件的项目。显然,您必须扩展.IsMatch()所有 7 个属性。