I created an arraylist of Student type. Student has name, subject information in it. Suppose my ArrayList has values like (sam, maths), (john, english), (mat, science). If i want to find out which student has science stream, then how to search it in an ArrayList.
I think it may be done by using binarysearch or indexof methods, but not getting it right.
Why did you created an arraylist of Student type ?
I'm pretty sure that you should go with a generic type-safe list : List<T>
To do your searches you could use LINQ :
List<Student> students = new List<Student>();
students.Add(new Student { Lastname = "Smith" });
students.Add(new Student { Lastname = "Foo" });
students.Add(new Student { Lastname = "SmithFoo" });
students.Add(new Student { Lastname = "SmithBar" });
var searchResults = from student in students
where student.Lastname.StartsWith("Smith")
select student;
This code will search in your students list and return three students : Smith, SmithFoo and SmithBar
Thats how I did in the end. Sorry I forgot to answer this one.
public int search(object sender, List<albums> al)
{
int i = -1;
TextBox txt = (TextBox)sender;
foreach (albums dc in al)
{
if ((dc.artist == txt) ||(dc.tag == txt))
{
i = (al.IndexOf(dc));
}
}
return i;
}
Related
I'm trying to access a class value by using a variable previously defined in dart, but I keep getting the error the operator [] isn't defined for the class
In Javascript I would access an object value using a variable like this:
let movie = {
movieTitle : 'Toy Story',
actor: 'Tom Hanks'
}
let actorName = 'actor';
console.log(movie[actorName]); // <- what I'm trying to replicate in dart
// expected output: Tom Hanks
Here is what I've tried and is throwing that error
class Movie {
String name;
String actor;
String producer;
}
void main() {
var movieTitle = new Movie();
movieTitle.name = 'Toy Story';
movieTitle.actor = 'Tom Hanks';
print(movieTitle.actor); <- prints out Tom Hanks as expected
var actorName = 'actor';
print(movieTitle[actorName]); <- throws error
}
I expect to be able to use a variable on the fly to access the value.
A trivial use case for me would be if I had a a list of Movie classes, where some actors and producers are null, I would like to filter on either non null actors or producer with a function like so:
List values = movieList.where((i) => i.actor != "null").toList(); // returns all Movies in movieList where the actor value isn't the string "null"
var actorIsNull = 'actor';
List values = movieList.where((i) => i[actorisNull] != "null").toList(); // throws error
You can createn a toMap() function in your Movie class and access properties using [] operator
class Movie {
String name;
String actor;
String producer;
Map<String, dynamic> toMap() {
return {
'name': name,
'actor' : actor,
'producer' : producer,
};
}
}
Now Movie class properties can be accessed as:
Movie movie = Movie();
movie.toMap()['name'];
You cannot access class members by a string containing their name. (Except with mirrors - outside the scope of this answer.)
You could remove the class altogether and just use a Map<String, String>.
Map<String, String> movie = {
'movieTitle': 'Toy Story',
'actor': 'Tom Hanks',
}
You could add some bool methods on the class.
bool hasNoActor() => actor == null;
...
List values = movieList.where((m) => !m.hasNoActor()).toList();
Or, you could pass a lambda to your mapper.
Movie movieTitle = Movie()
..name = 'Toy Story'
..actor = 'Tom Hanks';
Function hasActor = (Movie m) => m.actor != null;
List values = movieList.where(hasActor).toList();
I am facing this difficult.
I have this method:
public List findEmployees(String name) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Employee> c = cb.createQuery(Employee.class);
Root<Employee> emp = c.from(Employee.class);
c.select(emp);
c.distinct(true);
Join<Employee,Project> project =
emp.join("projects", JoinType.LEFT);
List<Predicate> criteria = new ArrayList<Predicate>();
if (name != null) {
ParameterExpression<String> p =
cb.parameter(String.class, "name");
criteria.add(cb.equal(emp.get("name"), p));
}
if (criteria.size() == 0) {
throw new RuntimeException("no criteria");
} else if (criteria.size() == 1) {
c.where(criteria.get(0));
} else {
c.where(cb.and(criteria.toArray(new Predicate[0])));
}
TypedQuery<Employee> q = em.createQuery(c);
if (name != null) { q.setParameter("name", name); }
return q.getResultList();
}
Basically, here I am getting the Employee.
What I want is to have an object different than employee, employee is related with projects and I want to return an object EmployeeProjectCount
That is basically an object with:
id (from employee)
name (from employee)
numberProjects (is the count of the related projects to an employee)
Projects is a table with a column named "employee" that makes the relation.
I am wondering if at my criteria builder I can do that, a count of the related fields
Is it possible to return a different object?
I cannot do this:
TypedQuery<EmployeeProjectCount> q = em.createQuery(c);
my jpql query is like this:
select e.id as id, e.name as name, count(e) as total
from
Employee e
left join Project p on p.employee = e.id group by e;
Is there any way to do it?
What you want to use is the construct method from CriteriaBuilder. It does exactly what you would otherwise use in jpql. You define the output class, and define the data that is used for it.
Here is a nice example of how to do this: How to select a POJO with a Criteria Query
private void createRooms()
{
myNeighbor = new HashMap <String, Room> ();
crumbs = new Item("Crumbs", "small crumbs of some kind of food", 100);
eggs = new Item("Raw Eggs", "a couple of raw eggs still contained within their egg shells", 1100);
cellPhone = new Item("Cell Phone", "Mike's cell phone he must have forgotten here...", 0);
textBooks = new Item("Textbooks", "Jay's textbooks, because he can't use his bedroom to store his stuff", 0);
poptarts = new Item("Pop Tarts", "an un-opened box of chocolate pop tarts that someone must have left behind...", 1500);
pizzaRolls = new Item("Pizza Rolls", "cooked steaming pizza rolls piled high", 2000);
clothes = new Item("Clothes", "clothes, a lot of clothes all over the floor and all over the room, who knows if they're clean or not...", 0);
// miningTools = new Item("Mining Tools", "pickaxes, drills, and everything else you need to extract rocks and minerals from the earth's crust", 100);
chips = new Item("Chips", "chip bag hidden away that is only half full now", 400);
hallway = new Room("in a dark hallway with crumbs scattered over the ground", crumbs);
kitchen = new Room("in a kitchen with raw eggs lying on the counter tops", eggs);
bathroom = new Room("in a bathroom with a stand up shower, a washer, a drier, and Mike's cell phone left behind laying on the counter", cellPhone);
livingRoom = new Room("in a living room with Jay's textbooks all over the room", textBooks);
upstairsLobby = new Room("in a lobby at the top of the stairs with a box of pop tarts on the ground", poptarts);
blakesRoom = new Room("in a dark room with towers of pizza rolls covering the desk and scattered across the bed", pizzaRolls);
jaysRoom = new Room("in a cluttered room with clothes covering every inch of the floor and nothing hanging on the walls", clothes);
mikesRoom = new Room("in a bed room with mining tools and a bag of chips hidden underneath a pillow on the bed", chips);
hallway.addNeighbor("north", kitchen);
hallway.addNeighbor("west", upstairsLobby);
hallway.addNeighbor("east", livingRoom);
kitchen.addNeighbor("west", bathroom);
kitchen.addNeighbor("south", hallway);
bathroom.addNeighbor("east", kitchen);
livingRoom.addNeighbor("west", hallway);
upstairsLobby.addNeighbor("north", jaysRoom);
upstairsLobby.addNeighbor("west", blakesRoom);
upstairsLobby.addNeighbor("east", mikesRoom);
upstairsLobby.addNeighbor("south", hallway);
blakesRoom.addNeighbor("east", upstairsLobby);
jaysRoom.addNeighbor("south", upstairsLobby);
mikesRoom.addNeighbor("west", upstairsLobby);
}
Room class
import java.util.HashMap;
/**
* Write a description of class Room here.
*
* #author (Christopher a date)
*/
public class Room
{
private String description;
private Item item;
private HashMap <String, Room> myNeighbor;
public Room (String pDescription)
{
description = pDescription;
item = null;
HashMap <String, Room> myNeighbor = new HashMap <String, Room> ();
}
public Room (String pDescription, Item pItem)
{
description = pDescription;
item = pItem;
}
public String getDescription()
{
return description;
}
public Item getItem()
{
return item;
}
public void addItem(Item i)
{
item = i;
}
public boolean hasItem()
{
if (item != null)
return true;
else
return false;
}
public void addNeighbor(String pDirection, Room r)
{
myNeighbor = new HashMap <String, Room> ();
myNeighbor.put(pDirection, r);
}
public Room getNeighbor(String pDirection)
{
Room next = myNeighbor.get(pDirection);
if(next != null){
return next;
}
else{
return null;
}
}
public Item removeItem()
{
Item temp;
temp = item;
item = null;
return temp;
}
public String getLongDescription()
{
String part1 = "You are " + description;
String part2 = "You see ";
if(item != null){
return part1 + "" + part2 + "" + item.getDescription() + "" + item.getCalories();
}
return part1;
}
}
Long story short, the point of this is to add Rooms and be able to naviage them and pick up items and drop them. It has just been brought to my attention as I try to run the program that I can't have multiple north/south/east/west keys. How can I get around this so I can make this work?
It wont allow me to comment so...
I am not sure what your ROOM class looks like but I am guessing it is intialized with a hasmap in the constuctor, and ahs a method called addNeighbor to actuallymodify this hash map?
----EDIT-----
Seeing your AddNeighbor method shows that you create a new hasmap every time you add a neighbor to the hashmap. There is no need and you alraedy craeted MyNeighbor in the constuctor, now you can just "put" they new key, value combination in the hash map
Just remove the line to create a new hasmap every time.
Assuming that you want to be able to write:
Room targetRoom = currentRoom.neighbour("north");
then you need to change your design.
The neighbours need to be member (ivars) of a room, like this for example:
class Room;
typedef HashMap<string, Room*> NeighbouringRooms;
public class Room {
...
public NeighbouringRooms const& neighbour() const {
return _neighbours;
}
private NeighbouringRooms neighbours;
}
(I've omitted some details inside the class, like adding a neighbour to a room.)
Now, since there are only 4 possible directions (N, S, E, W), an array of neighbours for each room would do the trick as well.
public class Room {
public Room neighbours[4];
...
}
Room room;
room.neighbour[north] = ... ;
I found a problem when i use the pivot control in the Windows Phone 8 SDK.
The pivot binds to a list named Students and set a button when click it,Will new a new student object and set it to Students[2] as new value. This has lead to the overlapping problem shown in the screenshot below. Has anyone else had this problem in the WP8 SDK?
Here is the code
public MainPage()
{
InitializeComponent();
this.DataContext = this;
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
InitiList();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
int index = 2;
Students[index] = new Student();
Students[index].Name = "tian";
Students[index].College = "shida";
}
private ObservableCollection<Student> _students;
public ObservableCollection<Student> Students
{
get { return _students; }
set
{
_students = value;
RaisePropertyChanged("Students");
}
}
private void InitiList()
{
Students = new ObservableCollection<Student>();
Students.Add(new Student { Name="a",College="aa"});
Students.Add(new Student { Name = "b", College = "aa" });
Students.Add(new Student { Name = "c", College = "aa" });
Students.Add(new Student { Name = "d", College = "aa" });
Students.Add(new Student { Name = "e", College = "aa" });
}
Ckeck this o/p image:
You're modifying Students but RaisePropertyChanged isn't getting fired because accessing Students doesn't fire Set, which calls RaisePropertyChanged. This could be the problem, I can't test it right now.
I experience the same issue, and I fixed it by adding the items to the ObservableCollection in the constructor instead of using the Add method. It appears to be a bug with the ObservableCollection class. Try changing your code to:
private void InitiList()
{
Students = new ObservableCollection<Student>(new [] {
new Student { Name="a",College="aa"}),
new Student { Name = "b", College = "aa" }),
new Student { Name = "c", College = "aa" }),
new Student { Name = "d", College = "aa" }),
new Student { Name = "e", College = "aa" })
});
}
I have a class Card, which has property Rank (1,2,3 etc) and I have a list of Cards and I wish to find all the Cards with the same Rank value in that list.
The list of Cards is sorted by Rank beforehand.
What would be the fasted way in .NET (using LINQ, if possible) to find all the objects with the same property value.
I don't know what the property value is beforehand, so I have to go through and compare. Until now I've been looping and keeping references to previous objects to compare, but I was wondering if there is not some easier way to do this?
Point is I need to be able to find N elements in a list with the same property value.
There might not be, but I thought I'd still ask.
You could group the cards by rank:
public class Card
{
public int Rank { get; set; }
}
class Program
{
static void Main()
{
var cards = new[]
{
new Card { Rank = 1 },
new Card { Rank = 2 },
new Card { Rank = 3 },
new Card { Rank = 2 },
new Card { Rank = 1 },
};
var groups = cards.GroupBy(x => x.Rank);
foreach (var group in groups)
{
Console.WriteLine("Cards with rank {0}", group.Key);
foreach (var card in group)
{
Console.WriteLine(card.Rank);
}
}
}
}
easiest would be to use linq
var results = myCardList.Select( c=>c.rank == myRank );
then you can iterate or convert to list.
Use Enumerable.ToLookup. The cards does not have to be sorted beforehand.
If you have a class
public class Card
{
public string Name { get; set; }
public int Rank { get; set; }
}
Then you can create a Lookup that groups per Rank like this
var cards = new Card[]{
new Card{Rank = 1, Name = "A"},
new Card{Rank = 1, Name = "B"},
new Card{Rank = 2, Name = "C"},
new Card{Rank = 3, Name = "D"},
};
var cardsByRank = cards.ToLookup(card => card.Rank);
foreach (var cardRankGroup in cardsByRank)
{
Console.WriteLine("KEY: " + cardRankGroup.Key);
foreach (var card in cardRankGroup)
{
Console.WriteLine(" Card: " + card.Name);
}
}
with the output
KEY: 1
Card: A
Card: B
KEY: 2
Card: C
KEY: 3
Card: D
Edit
if you want to extract all cards for a given Rank you can use rank as index to the lookup
foreach (var card in cardsByRank[2])
{
Console.WriteLine(" Card: " + card.Name);
}
Hey Tony, are you looking for something link this?
List<Card> rankedCards = cards.Where(o=> o.Rank == rank).ToList()
This should return a list of Cards that match the variable "rank" which I assume contains an int containing the value of Rank you want to match.