循环在字典中的数组内

时间:2012-03-26 20:24:39

标签: c#

您好我有一个简单的问题,这是使用C#在字典中的对象内循环的最简单方法吗? 字典包含组和组有一个名为tags的数组,我搜索了一个标记并返回包含该标记的组列表 我创建了一个解决方案但是当我应用它时会返回太多的双倍。

    List<Programme> toReturn = new List<Programme>();
        // might need to ask getprogramme service to do the iteriation and retun a value
        foreach (Programme programme in programmes.Values)
        {

            if (message.Programme.Tags[0] != null)
            {
                int i;
                int u;

                foreach (KeyValuePair<string, Programme> entry in programmes)
                {
                    // for (i = 0; i < message.Group.Tags.Length; i++)
                    for (i = 0; i < entry.Value.Tags.Length; i++)
                    //foreach (string i in message.Group.Tags)
                    {
                        for (u = 0; u < message.Programme.Tags.Length; u++)
                        {
                            // Compare the Name of the entry to the Name in the message (string comparison)
                            if (entry.Value.Tags[i].Equals(message.Programme.Tags[u]))
                            {
                                // If we found the group, set the return value and then break from the loop
                                toReturn.Add(programme);

                                break;
                            }


                        }
                    }
                }
            }

1 个答案:

答案 0 :(得分:2)

最简单的方法是使用LINQ:

var res = groups.Where(g => g.Value.Any(t => t.Equals("search_tag")));