C# linq DefaultIfEmpty() NullReferenceException Value cannot be empty. Parameter name: Source [duplicate] - c#

This question already has answers here:
Value cannot be null. Parameter name: source
(20 answers)
Closed 2 years ago.
I have a problem
How can I inquire in a linq correctly
Get a mistake NullReferenceException every time
public class Model
{
public int Nmb { get; set; }
public string _UserId { get; set; }
}
public static List<Model> _models_List { get; set; }
string user = "test name";
int test = _models_List.Where(o => o._UserId == user).Select(o => o.Nmb).DefaultIfEmpty(0).First();
if (test == 0)
{
Model obj = new Model();
obj._UserId = user;
obj.Nmb = 1;
_models_List.Add(obj);
}
I tried to correct the code like this
But I get the same mistake
NullReferenceException
Value cannot be empty. Parameter name: Source
int test = _models_List.Where(o => o._UserId == user).Select(o => o.Nmb).FirstOrDefault();
Please Help

The list _models_List is empty, to solve the issue replace the following code:
public static List<Model> _models_List { get; set; }
with:
public static List<Model> _models_List { get; set; } = new List<Model>();

Related

C# API Call: Null Exception at foreach loop [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 3 years ago.
I'm trying to map API JSON data into some properties of a class, and I'm getting the error below. I was able to narrow down the data entry causing this issue.
[The value for PositionDateStart]
The script successfully creates an object off the properties, but once I call the object to test it using a foreach loop, it crashes and gives me this error.
My question is what could I write to tell the script to replace null with today's date if this comes up.
Thanks in advance!
Error Message:
NullReferenceException: Object reference not set to an instance of an object.
JSON Results #Console.WriteLine(json)
[
{
"EntryID": 41992,
"Position": "Associate",
"PositionDateEnd": "2020-05-15T00:00:00",
"PositionDateStart": null
}
]
Script
var json = await response.Content.ReadAsStringAsync();
Console.WriteLine(json); //JSON results above
var result = JsonConvert.DeserializeObject<List<Properties>>(json);
//Point at which code errors outs
foreach (var item in result)
{
Console.WriteLine(item.PositionDateStart);
Console.WriteLine(item.PositionDateStart.GetType());
}
Class Properties
public class Properties
{
public int EntryID { get; set; }
public string Position { get; set; }
public DateTime? PositionDateEnd { get; set; }
public DateTime? PositionDateStart { get; set; }
}
You can simply assign current date if PositionDateStart is null then output to console anyway without errors since it will never be empty:
//Point at which code errors outs
foreach (var item in result)
{
if (item.PositionDateStart == null)
item.PositionDateStart = DateTime.Now;
Console.WriteLine(item.PositionDateStart);
Console.WriteLine(item.PositionDateStart.GetType());
}
EDIT
As asked in comment, if you prefere to modify the class itself here is a variant through the get accessor so your foreach remains the same:
public class Properties
{
public int EntryID { get; set; }
public string Position { get; set; }
public DateTime? PositionDateEnd { get; set; }
private DateTime? _positionDateStart;
public DateTime? PositionDateStart
{
get { return _positionDateStart == null ? DateTime.Now : _positionDateStart; }
set { _positionDateStart = value; }
}
}
Try (not tested):
Console.WriteLine(item?.PositionDateStart ?? DateTime.Now);
The null condional and null coalese operators are explained here
try the following code:
foreach (var item in result)
{
if(item.PositionStartDate == null)
{
item.PositionDateStart = DateTime.Now;
}
Console.WriteLine(item.PositionDateStart.GetType());
}

unable to convert a class model properties to list in.net

This is my code of class
public class WMBillable
{
public string Month { get; set; }
public int Year { get; set; }
public int MonthNum { get; set; }
}
this is my method which contains:
foreach (var dt in lDistinctDate)
{
WMNB = new WMBillable();
DateTime Cur = new DateTime();
Cur = Convert.ToDateTime(dt.InvoiceDate);
WMNB.MonthNum = Convert.ToInt32(Cur.Month);
WMNB.Year = Convert.ToInt32(Cur.Year);
lstWMB.Add(WMNB);
}
var CurrentMonthYear = lstWMB.OrderByDescending(item => item.Year).ThenBy(x => x.Month).FirstOrDefault();
List<WMBillable> lstQu = CurrentMonthYear.ToList();
in this line of code List<WMBillable> lstQu = CurrentMonthYear.ToList(), I am unable to convert the extracted linq query to a list. I got the error like "WMBillable does not contain a definition for ToList() and no extension method toList accepting a first argument of type WMBillable could be found".
If I go for auto correction it is generating internal list inside my model class like this
public class WMBillable
{
public string Month { get; set; }
public int Year { get; set; }
public int MonthNum { get; set; }
internal List<WMBillable> ToList()
{
throw new NotImplementedException();
}
}
I have no idea to correct this..Kindly help this dot net beginner.
You are calling FirstOrDefault:
var CurrentMonthYear = lstWMB.OrderByDescending(item => item.Year).ThenBy(x => x.Month).FirstOrDefault();
By this you either get the FIRST or DEFAULT value, which is just ONE.
Try:
var CurrentMonthYear = lstWMB.OrderByDescending(item => item.Year).ThenBy(x => x.Month);
which will return an IEnumerable collection which can be converted to list.
MSDN FirstOrDefault
var CurrentMonthYear = lstWMB.OrderByDescending(item => item.Year).ThenBy(x => x.Month);
List<WMBillable> lstQu = CurrentMonthYear.ToList();
Remove FirstOrDefault function call, then you will be able to convert.

Filling POCO Object with List inside a List [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
I´m attempting to fill a POCO object but I get the NullReferenceException - Object reference not set to an instance of an object, at line "objectAreas.position.Add(objectPositions);" I think I'm not initializing well but I don't see my mistake, let's see the code:
POCO OBJECT
public class GenericQuery
{
public sealed class Areas
{
public int idarea { get; set; }
public string areaname { get; set; }
public List<Positions> positions { get; set; }
}
public sealed class Positions
{
public int idposition { get; set; }
public string positionname { get; set; }
}
public sealed class QueryAreasPositions
{
public int code { get; set; }
public string response { get; set; }
public List<Areas> areas { get; set; }
}
}
Filling It
GenericQuery.QueryAreasPositions objectAreasPositions = new GenericQuery.QueryAreasPositions();
var query = areaRepository.Get(); //Eager Loading EntityFramework List Object, see the AreaRepository at the end
objectAreasPositions.code = 123;
objectAreasPositions.response = "anything";
foreach (var area in query)
{
GenericQuery.Areas objectAreas = new GenericQuery.Areas();
objectAreas.idarea = area.IdArea;
objectAreas.areaname = area.Name;
foreach (var position in area.Position)
{
GenericQuery.Positions objectPositions = new GenericQuery.Positions();
objectPositions.idposition = position.IdPosition;
objectPositions.positionname = position.Name;
***objectAreas.position.Add(objectPositions);***//HERE
}
objectAreasPositions.areas.Add(objectAreas); //And maybe here
}
AreaRepository
public List<Area> Get()
{
using (var context = new Entities())
{
return context.Area.Include("Position").ToList();
}
}
I would appreciate any help/guide you can give me, Thanks.
You are never initializing objectAreas.position, hence the default value for a List<T> is null.
Since you are trying to call the Add method on a null reference, you are getting a NullReferenceException.
To fix this, you should initialize the property before using it:
objectAreas.position = new List<GenericQuery.Positions>();
Alternatively, you can add this logic on GenericQuery.Areas constructor, which would be more appropriate:
public sealed class Areas
{
public int idarea { get; set; }
public string areaname { get; set; }
public List<Positions> positions { get; set; }
public class Areas()
{
positions = new List<Positions>();
}
}
Shouldn't you rather be doing like below. Your position is null cause not yet initialized and thus the said exception.
objectAreas.position = new List<Position>();
objectAreas.position.Add(objectPositions);

why null reference exception in List<decimal> [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
i have a problem, i created an object in C# like this:
public class logis
{
public string codigo { get; set; }
public List<decimal> Necesidades { get; set; }
decimal SumaNecesidades{get;set;}
}
then i do something like this:
logisva logi = new logis();
logi.codigo = oDataReader.GetValue(0).ToString();
logi.Necesidades.Add(0);
But when i execute my code i get a null reference exception error. Object reference not set to an instance of an object. on the last line logi.Necesidades.Add(0);
Any idea why i get this error?
In C# the properties do not initialize/create the List<ofType> object automatically. You need to create the list explicitely:
public class logis
{
public string codigo { get; set; }
public List<decimal> Necesidades { get; set; }
decimal SumaNecesidades{get;set;}
public logis()
{
this.Necesidades = new List<decimal>();
}
}
Another option is to create the list in the getter resp. setter (so to say your own lazy initialization, downside - introduces more code, advantage no need to override every contructor):
public class logis
{
public string codigo { get; set; }
decimal SumaNecesidades{get;set;}
private List<decimal> necesidades = null;
private void initNecesidades()
{
if (this.necesidades == null)
{
this.necesidades = new List<decimal>();
}
}
public List<decimal> Necesidades
{
get
{
this.initNecesidades();
return this.necesidades;
}
set
{
this.initNecesidades();
this.necesidades = value;
}
}
}
Yet another option would be to use the new C# 6.0 features (if it is an option to use/already using the latest .NET Framework version) as already suggested in the comments by #Jcl:
public List<decimal> Necesidades { get; set; } = new List<decimal>()

How to compare Two Object -Exclude specific Properties in Comparison [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I have a case there I want to compare two objects in c#.Also I would have option to exclude specific properties when comparing. Can anyone suggest a better approach. Class will look like as below
public class Address
{
public string AddressID { get; set; }
public int AddressStagingID { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string County { get; set; }
public string Postcode { get; set; }
public string Country { get; set; }
public bool PreferredAddress { get; set; }
public int? DBID { get; set; }
public Enum AddressStatus Status { get; set; }
}
I need to have a function like
private bool IsAddressModified(Address currentAddress,Address existingAddress)
{
}
Compare NET Objects have everything you need!
Ignore By Expression
CompareLogic compare = new CompareLogic();
compare.Config.IgnoreProperty<Person>(x => x.Name);
Ignore By the ClassName.MemberName
CompareLogic compare = new CompareLogic();
compare.Config.MembersToIgnore.Add("Person.Name");
Ignore All Members with a Name
CompareLogic compare = new CompareLogic();
compare.Config.MembersToIgnore.Add("UpdateDate");
Ignore with a Wildcard
CompareLogic compare = new CompareLogic();
compare.Config.MembersToIgnore.Add("*Id");
Ignore with an Attribute
[AttributeUsage(AttributeTargets.Property)]
public sealed class CompareIgnoreAttribute : Attribute
{
}
public class Shipment
{
public long IdentCode { get; set; }
public String Customer { get; set; }
[CompareIgnore]
public DateTime InsertDate { get; set; }
}
CompareLogic compare = new CompareLogic();
compare.Config.AttributesToIgnore.Add(typeof(CompareIgnoreAttribute));
Compare Only Properties with an Attribute
public class Movie
{
[Compare]
public string Name { get; set; }
public decimal PaymentForTomCruise { get; set; }
}
CompareLogic compare = new CompareLogic();
compare.Config.RequiredAttributesToCompare.Add(typeof(CompareAttribute));
I tried to develop a different solution using Expression Trees which is, in my opinion, more flexible
public class Test
{
public static void Main()
{
Address a1 = new Address();
a1.AddressID = "100";
Address a2 = new Address();
a2.AddressID = "200";
Console.WriteLine(IsAddressModified(a1,a2,a=>a.AddressID));
}
public static bool IsAddressModified(Address a1,Address a2,params Expression<Func<Address,Object>>[] props)
{
if(props == null)
return a1.Equals(a2);
foreach(Expression<Func<Address,object>> memberExpression in props)
{
MemberExpression property = memberExpression.Body as MemberExpression;
if(property != null)
{
foreach(PropertyInfo pi in typeof(Address).GetProperties())
{
// exclude all properties we passed in
if(!pi.Name.Equals(property.Member.Name))
{
var valueA1 = pi.GetValue(a1);
var valueA2 = pi.GetValue(a2);
if(valueA1 != null && valueA2 != null)
if(!valueA1.Equals(valueA2))
return true;
}
}
}
}
return false;
}
}
So what does the code?
You can pass an array of 'properties' to the method IsAddressModified. These properties will be excluded while comparing.
From the Expression I extract a MemberExpression to get the Name of each Property.
I iterate through all Properties the type Address has and check if it is one property to exclude.
Last but not least, I compare the property values.
Why so 'complicated' ?
With this solution you can pass as much properties into the function as you like AND you are totally type-safe during compilation.
In the Main you can see how I call this function. Even due to the fact that AddressID of a1 and a2 differ, the function returns false, because you excluded the AddressID.
A full compilable example can be found here
How about Reflection:
private bool IsAddressModified(Address currentAddress, Address existingAddress)
{
foreach (PropertyInfo pi in currentAddress.GetType().GetProperties())
{
//To exclude properties use condition
if (pi.Name != "City") {
object currentElement = typeof(Address).GetProperty(pi.Name).GetValue(currentAddress,null);
object existingElement = typeof(Address).GetProperty(pi.Name).GetValue(existingAddress,null);
if (!currentElement.Equals(existingElement))
{ return false; }
}
return true;
}
}
If you are looking for something very simple, use reflection. But if you need something advanced, use CompareObjects. Here is the Nuget. This library can give detailed reports on changes as well. Which means you can use it for logging etc.
This is a sample code from the site.
//This is the comparison class
CompareLogic compareLogic = new CompareLogic();
//Create a couple objects to compare
Person person1 = new Person();
person1.DateCreated = DateTime.Now;
person1.Name = "Greg";
Person person2 = new Person();
person2.Name = "John";
person2.DateCreated = person1.DateCreated;
ComparisonResult result = compareLogic.Compare(person1, person2);
//These will be different, write out the differences
if (!result.AreEqual)
Console.WriteLine(result.DifferencesString);
Brute force?
private bool IsAddressModified(Address a, Address b)
{
return a.Address1 != b.Address1 || a.Address2 != b.Address2
|| a.City != b.City || a.PostCode != b.PostCode;
// etc. for all the properties that are considered as modified
}

Categories

Resources