Answer the question
In order to leave comments, you need to log in
How to access a specific element of a list by two keys without iterating through the list?
How to access a specific list element by two keys x, y without iterating through the list?
something like ListPixels.xy
without iterating over the list each time foreach
public class LPixels
{
public static List<Pixels> ListPixels = new List<Pixels>();
}
public class Pixels
{
public int x;
public int y;
public string text;
}
Answer the question
In order to leave comments, you need to log in
LINQ
class Program
{
static void Main()
{
var lpixels = new LPixels();
lpixels.ListPixels.Add(new Pixels(1, 1, "test11"));
lpixels.ListPixels.Add(new Pixels(1, 2, "test12"));
lpixels.ListPixels.Add(new Pixels(2, 1, "test21"));
var find = lpixels.ListPixels.First(x => x.x == 1 && x.y == 2);
Console.WriteLine(find.text);
}
}
public class LPixels
{
public List<Pixels> ListPixels = new List<Pixels>();
}
public class Pixels
{
public Pixels (int x, int y, string text)
{
this.x = x;
this.y = y;
this.text = text;
}
public int x;
public int y;
public string text;
}
You can, but it's still a wrapper over the loop
//Один элемент
var result = ListPixels.SingleOrDefault(x=> x.x = someX && x.y = someY);
//Первый элемент
result = ListPixels.FirstOrDefault(x=> x.x = someX && x.y = someY);
//коллекция элементов
var results = ListPixels.Where(x=> x.x = someX && x.y = someY);
It is possible to be slightly perverted and to make an indexer. something like this
public class Pixel
{
public int X {get;set}
public int Y {get;set}
public string Text {get;set}
}
public class LPixels
{
public List<Pixel> ListPixels = new List<Pixel>();
public Pixel this[int x, int y]
{
get
{
return ListPixels.FirstOrDefault(px => px.X == x && px.Y == y);
}
set
{
var point = ListPixels.FirstOrDefault(px => px.X == x && px.Y == y);
if(point != null)
{
point.Text = value.Text;
}
else
{
var newPoint = new Point
{
X = x;
Y = y;
Text = value.Text;
}
ListPixels.Add(newPoint);
}
}
}
}
var lpixels = new LPixels();
var result = lpixels[1, 2];
lpixels[1, 2] = new Point { Text = "Test" };
If you really need a quick search, then you should use hash tables, at least the same Dictionary.
It is enough to declare a class to public class Pixels : IEquatable<Pixels>
declare methods:
public bool Equals(Pixels p)
{
return x == p.x && y == p.y;
}
public override int GetHashCode()
{
return x.GetHashCode() ^ y.GetHashCode();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question