Where clause on linq query against dictionary?
I have fixed the problem of it not listing the data which was related to a wrong field on the spawn dictionary but still i would like to question if the way I am approaching it is ok ?
I have a few checkboxs that if true should add check the item status and include it on the 开发者_StackOverflow中文版list.
So not really knowing what to do, this is what I came up with:
HashSet<int> status = new HashSet<int>();
if (OptionsForm.filterPlayer.Checked) status.Add(0);
if (OptionsForm.filterEnemy.Checked) status.Add(1);
if (OptionsForm.filterSummon.Checked) status.Add(2);
if (OptionsForm.filterNPC.Checked) status.Add(3);
if (OptionsForm.filterObject.Checked) status.Add(4);
if (OptionsForm.filterMonster.Checked) status.Add(5);
if (OptionsForm.filterGatherable.Checked) status.Add(6);
if (OptionsForm.filterUnk.Checked) status.Add(7);
var query = from SpawnList item in spawnEntities.Values
where status.Contains(item.Status)
orderby item.Name ascending
select item;
But currently it is not returning me any errors or items that should have been returned.
spawnEntities is a dictionary with uint, SpawnList.
SpawnList is a simple class:
public class SpawnList
{
public string Name { get; set; }
public int Status { get; set; }
// some more data not needed for the question
}
it was my mistake, the status on the dictionary was wrong in 1 field and i was not getting what I wanted after listing all the data I noticed it heh, but is it ok to do it like I am doing ?
To avoid such mistakes, I would use enumerations instead of ints - just define
enum SomeStatus
{
Player,
Enemy,
<.etc.>
}
and change
public int Status { get; set; }
into
public SomeStatus Status { get; set; }
My comment to the previous answered byt further explained. You can use the Flags
attribute instead, which will make it easier to check your status.
[Flags]
enum YourEnum
{
none,
Val1,
Val2,
Val3,
Val4,
}
Set your status to:
public YourEnum Status {get; set;}
Create your combined status like:
YourStatus status = YourEnum.None;
if(OptionsForm.filterPlayer.Checked) status = status | YourEnum.Val1;
if(OptionsForm.filterEnemy.Checked) status = status | YourEnum.Val2;
<etc>
The you'll get a linq like:
var query = from SpawnList item in spawnEntities.Values
where status & itemStatus != YourEnum.None
orderby item.Name ascending
select item;
Read more about the flags attribute here: http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx
精彩评论