How to Check If Object Already Exists in a List

how to check if object already exists in a list

It depends on the needs of the specific situation. For example, the dictionary approach would be quite good assuming:

  1. The list is relatively stable (not a lot of inserts/deletions, which dictionaries are not optimized for)
  2. The list is quite large (otherwise the overhead of the dictionary is pointless).

If the above are not true for your situation, just use the method Any():

Item wonderIfItsPresent = ...
bool containsItem = myList.Any(item => item.UniqueProperty == wonderIfItsPresent.UniqueProperty);

This will enumerate through the list until it finds a match, or until it reaches the end.

Check if object with specific value exists in List

You can use Any(),

Any() from Linq, finds whether any element in list satisfies given
condition or not, If satisfies then return true

if(ListA.Any(a => a.Id == stringID))
{
//Your logic goes here;

}

MSDN : Enumerable.Any Method

Check if object already exists in object

To get the property name of an object you can use Object.keys(). The first problem solved.

Now we need to iterate through the whole object including nested objects. This is the second problem.

And compare it to a query object. This is the third problem.

I assume that we have an object that only contains "simple" though nested objects with primitive values (I do not consider objects with functions or arrays)

// let's assume we have this object
const information = {
city: {
Streetname: 'streetname1'
},
house: {
color: "blue",
height: 100,
city: {
findMe: { Streetname: '' } // we want to get the path to this property 'findMe'
}
},
findMeToo: {
Streetname: '' // we also want to get the path to this proeprty 'findMeToo'
},
willNotFindMe: {
streetname: '' // case sensetive
}
}

// this is our object we want to use to find the property name with
const queryObject = {
Streetname : ''
}

If you use === to compare Objects you will always compare by reference. In our case, we are interested to compare the values. There is a rather extensive checking involved if you want to do it for more complex objects (read this SO comment for details), we will use a simplistic version:

// Note that this only evaluates to true if EVERYTHING is equal.
// This includes the order of the properties, since we are eventually comparing strings here.
JSON.stringify(obj1) === JSON.stringify(obj2)

Before we start to implement our property pathfinder I will introduce a simple function to check if a given value is an Object or a primitive value.

function isObject(obj) {
return obj === Object(obj); // if you pass a string it will create an object and compare it to a string and thus result to false
}

We use this function to know when to stop diving deeper since we reached a primitive value which does not contain any further objects. We loop through the whole object and dive deeper every time we find a nested object.

function findPropertyPath(obj, currentPropertyPath) {
const keys = isObject(obj) ? Object.keys(obj) : []; // if it is not an Object we want to assign an empty array or Object.keys() will implicitly cast a String to an array object
const previousPath = currentPropertyPath; // set to the parent node

keys.forEach(key => {
const currentObj = obj[key];
currentPropertyPath = `${previousPath}.${key}`;

if (JSON.stringify(currentObj) === JSON.stringify(queryObject)) console.log(currentPropertyPath); // this is what we are looking for
findPropertyPath(currentObj, currentPropertyPath); // since we are using recursion this is not suited for deeply nested objects
})
}

findPropertyPath(information, "information"); // call the function with the root key

This will find all "property paths" that contain an object that is equal to your query object (compared by value) using recursion.

information.house.city.findMe
information.findMeToo

How to check if an object already exists in list of objects using C#

You can also use a HashSet:

public class ClassStudents {

public Id {get; set;}
public Name {get; set;}

public override bool Equals(object obj) {
return this.Name.Trim().ToLower().Equals(((ClassStudents)obj).Name.Trim().ToLower());
}

public override int GetHashCode() {
return this.Name.GetHashCode();
}
}

In your main(), you can declare a HashSet like below:

HashSet <ClassStudents> hash = new HashSet<ClassStudents>();

Now, this will add only unique elements in the set.

flutter: check if object already exist in the list

favlist.items.contains and favlist.items.indexof are not working because I assume you are checking if favoriteitem exists (which it never will because it is a brand new object you just created). I would suggest checking by some unique identifier. Without knowing too much about your project, I would suggest something like the following:

Assuming your link field is unique per favorite item, the following should help:

//this is your new created favoriteitem to check against
final favoriteitem = new FavoriteItem(headline: item['headline'], content: item['content'], link: item['link'], publisheddate: item['publisheddate']);

//find existing item per link criteria
var existingItem = items.firstWhere((itemToCheck) => itemToCheck.link == favoriteitem.link, orElse: () => null);

If existingItem is null, then nothing exists in your list that matches that link, otherwise it will return the first item matching that link.

Check to see if an object already exists in the List

As mentioned by shmosel, .contains() only works when equals() and hashCode() methods implemented correctly.

If such question appeared, it would be nice to you google and read more about these methods. For example

Overriding the java equals() method - not working?

Why do I need to override the equals and hashCode methods in Java?

In short, equals() tells java how to compare your objects

hashCode() tells how to generate the hashcode! It used by some algorythms or data structures like Set or Map to keep objects and allows to search objects faster within the data structure

Little hint, often your IDE can generate equals() and hashCode() methods for you.

For example in IntellijIdea you can open Produto class and press alt-insert -> equals() and hashCode()

How to check if a specific object already exists in an array before adding it

If your object is created earlier and has the same reference as the one in the array, you can use indexOf:

var myObj = { a: 'b' };
myArray.push(myObj);
var isInArray = myArray.indexOf(myObj) !== -1;

Otherwise you can check it with find:

var isInArray = myArray.find(function(el){ return el.id === '123' }) !== undefined;

Check if object value exists within a Javascript array of objects and if not add a new object to array

I've assumed that ids are meant to be unique here. some is a great function for checking the existence of things in arrays:

const arr = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' }];
function add(arr, name) { const { length } = arr; const id = length + 1; const found = arr.some(el => el.username === name); if (!found) arr.push({ id, username: name }); return arr;}
console.log(add(arr, 'ted'));


Related Topics



Leave a reply



Submit