检查Session中是否已存在数组

时间:2013-05-05 11:17:46

标签: c# asp.net arrays list session

在Visual C#中,如何检测Session中是否已存在数组?该网站有一个TextBox,你可以写一个名字。单击“单击”按钮时,它会在标签中添加名称。假设我添加了相同的名称,它应该在标签中显示一条消息,如“名称已存在!”。我该怎么办?我读到了“包含”方法,但对我来说效果不佳。我犯了什么错误?

以下代码为:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void btnClick_Click(object sender, EventArgs e)
    {
        if (Session["listOfCharacters"] == null) 
        {
            Session.Add("listOfCharacters", new List<Character>());
        }

        List<Character> listOfCharacters = (List<Character>)Session["listOfCharacters"];

        listOfCharacters.Add(new Character() { name = txtName.Text});

        lblShow.Text = "";

        foreach (Character item in listOfCharacters)
        {
            lblShow.Text += "Name: " + item.name + "<br />";

        //if (listOfCharacters.Contains(Session["listOfCharacters"]))
        //{
        //    lblShow.Text = "Exists";
        //}
        }
    }
}

相信我,花了我几个小时和几天,但尚未找到解决方案。

4 个答案:

答案 0 :(得分:1)

您可以编写LINQ查询以检查列表中是否存在该项目

e.g。

private string _listofcharacters = "listOfCharacters";
protected void Button1_Click(object sender, EventArgs e)
{
    if (Session[_listofcharacters] == null)
    {
        Session.Add(_listofcharacters, new List<Character>());
    }

    List<Character> listOfCharacters = (List<Character>)Session[_listofcharacters];

    lblShow.Text = "";

    var check = from p in listOfCharacters
                where p.Name.ToLower().Contains(txtName.Text.ToLower())
                select p;

    if (check.Count() == 0)
    {
        listOfCharacters.Add(new Character() { Name = txtName.Text });

        foreach (Character item in listOfCharacters)
        {
            lblShow.Text += "Name: " + item.Name + "<br />";
        }
    }
    else
    {
        lblShow.Text = "Name already exists!";
    }
}

答案 1 :(得分:0)

您必须在列表中进行检查,并且看到Character的属性name与文本框中的新文本相同。您可以使用LINQ:

if (listOfCharacters.Any(c => c.name == txtName.Text)) 
    lblShow.Text = "Name already exists!";

如果你使用List<string>那么它会更容易,因为你可以像这样使用Contains方法:

List<string> listOfCharacters = ...
....
if (listOfCharacters.Contains(txtName.Text)) 
    lblShow.Text = "Name already exists!";

为了获得额外的效果,请勿使用List<string>,而是使用HashSet<string>

因此,如果您只是要包含一个包含该名称的字符类,那么我建议:丢失该类并使用List<string>

您的代码将成为:

protected void btnClick_Click(object sender, EventArgs e)
{
    List<string> listOfNames = Session["listOfNames"] as List<string>;
    if (listOfNames == null)
        Session["listOfNames"] = listOfNames = new List<string>();

    if (listOfNames.Contains(txtName.Text))
    {
        lblShow.Text = "Name already exists!";
    }
    else
    {
        listOfNames.Add(txtName.Text);
        lblShow.Text = String.Join("<br />", listOfNames);
    }
}

答案 2 :(得分:0)

实体:

public class Character
{
    public string Name;
}

的Comparer

public class CharacterComparer : IEqualityComparer<Character>
{
    public bool Equals(Character x, Character y)
    {
        if (ReferenceEquals(x, y))
        {
            return true;
        }

        if (ReferenceEquals(x, null) || ReferenceEquals(y, null))
        {
            return false;
        }

        // Ignore case and culture
        return string.Compare(x.Name, y.Name, StringComparison.InvariantCultureIgnoreCase) == 0;
    }

    public int GetHashCode(Character obj)
    {
        if (obj == null || string.IsNullOrEmpty(obj.Name))
        {
            return 0;
        }

        return obj.Name.GetHashCode();
    }
}

使用HashSet。

        HashSet<Character> characters1 = new HashSet<Character>(new CharacterComparer());
        characters1.Add(new Character {Name = "Alex"});
        characters1.Add(new Character { Name = "Peter" });
        characters1.Add(new Character { Name = "John" });

        HashSet<Character> characters2 = new HashSet<Character>(new CharacterComparer());
        characters2.Add(new Character { Name = "John" });
        characters2.Add(new Character { Name = "Jenny" });

        characters2.IntersectWith(characters1);

        Console.WriteLine("Existing count: " + characters2.Count);

输出:

Existing count: 1

编辑1

不要在会话列表中添加新项目:

 listOfCharacters.Add(new Character() { name = txtName.Text});

您已经添加了新的字符列表,然后尝试在同一列表中找到它。您应该使用单独的列表。会话列表(现有字符)和要添加字符的新列表。

添加

using System.Linq;

并遍历新列表以搜索会话列表中的现有用户

// characters2 = created new list with Characters to be added
foreach (var item in characters2)
{
    Character character = item;
    // characters1 = obtained from sessions
    bool contains = characters1.Contains(character, new CharacterComparer());
    if (contains)
    {
        Console.WriteLine("Character {0} exists", character.Name);
    }
}

答案 3 :(得分:-1)

只需检查会话是空还是空。您可以使用字符串对象的IsNullOrEmpty函数。

 if(!string.IsNullOrEmpty(Session["listOfCharacters"] as string)){
          lblShow.Text = "Exists";
  }

但Stackoverflow上也有类似的问题。