2

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

以下代码是:

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

4 回答 4

1

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

例如

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!";
    }
}
于 2013-05-05T13:26:54.433 回答
0

您必须遍历您的列表并查看nameCharacter 的属性与文本框中的新文本相同。您可以使用 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>but 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);
    }
}
于 2013-05-05T11:25:54.430 回答
0

实体:

public class Character
{
    public string Name;
}

比较器

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<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);
    }
}
于 2013-05-05T12:01:39.147 回答
-1

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

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

不过 Stackoverflow 上也有类似的问题。

于 2013-05-05T11:27:05.480 回答