我正在制作一个c#应用程序,我使用多个组合框在数据网格视图上过滤项目,每个组合框的列表顶部都有“全部”,如果选中,它将不会在DGV项目中应用过滤器。我已经编写了代码,但是当同时应用2个过滤器时,查询速度很慢,我还没有完成其余的过滤器,直到我知道我使用的方法是否最佳。
namespace HDA_InfoBook
{
public partial class frmGallery : Form
{
HDAEntities HDA = new HDAEntities();
IQueryable<Hero> firstQuery = null;
IQueryable<Hero> finalQuery = null;
public frmGallery()
{
InitializeComponent();
}
public void ViewResults(IQueryable<Hero> viewResult)
{
var gridSource = from r in viewResult
select new
{
Name = r.Name,
Rarity = r.Rarity,
Speed = r.Speed,
Attack = r.Attack,
Target = r.Target
};
dgdResult.DataSource = gridSource.ToList();
}
public void InitializeQuery()
{
firstQuery = from hero in HDA.CharactersNames
orderby hero.HeroRarity
select new Hero
{
ID = hero.ID,
Name = hero.HeroName,
RarityID = hero.HeroRarity,
Rarity = hero.Rarity.RarityName,
Speed = hero.Initiative,
Attack = hero.Attack,
Target = hero.Attack2.Description
};
ViewResults(firstQuery);
}
public void ReloadAll()
{
finalQuery = firstQuery;
}
public void FilterRarity(int rarityId)
{
finalQuery = from o in finalQuery
where o.RarityID == rarityId
select new Hero
{
ID = o.ID,
Name = o.Name,
RarityID = o.RarityID,
Rarity = o.Rarity,
Speed = o.Speed,
Attack = o.Attack,
Target = o.Target
};
}
public void FilterGroup(int groupId)
{
var subQuery = from hero in HDA.Hero_Group
where hero.GroupID == groupId
select hero.HeroID;
finalQuery = from o in finalQuery
where subQuery.Contains(o.ID)
select new Hero
{
ID = o.ID,
Name = o.Name,
RarityID = o.RarityID,
Rarity = o.Rarity,
Speed = o.Speed,
Attack = o.Attack,
Target = o.Target
};
}
public void ApplyFilter()
{
ReloadAll();
if (cboRarity.SelectedIndex != 0)
FilterRarity(cboRarity.SelectedIndex);
if (cboGroup.SelectedIndex != 0/*-1 && cboGroup.ValueMember != ""*/)
FilterGroup((byte)cboGroup.SelectedValue);
//FilterGroup(cboGroup.SelectedIndex);
ViewResults(finalQuery);
}
private void cboRarity_SelectedIndexChanged(object sender, EventArgs e)
{
ApplyFilter();
}
private void cboGroup_SelectedIndexChanged(object sender, EventArgs e)
{
ApplyFilter();
}
}
}
令人沮丧的是,当我应用第三个过滤器时,查询时间大大减少,为什么会这样?
这工作得更快
public void ApplyFilter2()
{
var subQuery = from hero in HDA.Hero_Group
where hero.GroupID == ((byte)cboGroup.SelectedValue)
select hero.HeroID;
var q = from o in HDA.CharactersNames
select new
{
ID = o.ID,
Name = o.HeroName,
RarityID = o.HeroRarity,
Rarity = o.Rarity.RarityName,
Speed = o.Initiative,
Attack = o.Attack,
Target = o.Attack2.Description
};
if (cboRarity.SelectedIndex != 0)
q = q.Where(o => o.RarityID == cboRarity.SelectedIndex);
if (cboGroup.SelectedIndex != 0)
q = q.Where(o => subQuery.Contains(o.ID));
if (cboSpeed.SelectedIndex != 0)
q = q.Where(o => o.Speed == cboSpeed.SelectedIndex);
dgdResult.DataSource = q.ToList();
}