?
Solved

Linq query filter List

Posted on 2016-08-15
6
Medium Priority
?
88 Views
Last Modified: 2016-08-17
Hi All

I have below query. I want to filter items and do not want to add new salesOrders()  where startDate is Empty.
If startDate is Empty I want to remove it.

req.sOrders = (from document in resp.transaction.quote_data.sub_documents
                                      let values = document.attributes[0].value.ToString().Split(new[] { "**" }, StringSplitOptions.None)
                                      where (document.attributes != null && document.attributes.Length > 0) && !string.IsNullOrWhiteSpace(document.attributes[0].value.ToString())
                                      select new salesOrder()
                                      {
                                          productCode = values[1],
                                          salesOrderType = values[2],
                                          startDate = String.IsNullOrEmpty(values[3])? "" : DateTime.Parse(values[3]).ToString("yyyy-MM-dd"),
                                          pays = !string.IsNullOrWhiteSpace(values[4]) ? int.Parse(values[4]) : 0,
                                          scns = (from code in values[5].Split(new[] { "$$" }, StringSplitOptions.RemoveEmptyEntries) select new scns() { scnCode = (String.IsNullOrEmpty(code)? null : code)  }).ToList()
                                      }).ToList();
0
Comment
Question by:Member_2_7967608
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
6 Comments
 
LVL 34

Expert Comment

by:it_saige
ID: 41756785
Just move the string.IsNullOrEmpty(value[3]) to your where statement and add a not operator; e.g. -
req.sOrders = (from document in resp.transaction.quote_data.sub_documents
			let values = document.attributes[0].value.ToString().Split(new[] { "**" }, StringSplitOptions.None)
			where (document.attributes != null && document.attributes.Length > 0) && !string.IsNullOrWhiteSpace(document.attributes[0].value.ToString()) && !string.IsNullOrEmpty(values[3])
			select new salesOrder()
			{
				productCode = values[1],
				salesOrderType = values[2],
				startDate = DateTime.Parse(values[3]).ToString("yyyy-MM-dd"),
				pays = !string.IsNullOrWhiteSpace(values[4]) ? int.Parse(values[4]) : 0,
				scns = (from code in values[5].Split(new[] { "$$" }, StringSplitOptions.RemoveEmptyEntries) select new scns() { scnCode = (String.IsNullOrEmpty(code) ? null : code) }).ToList()
			}).ToList();

Open in new window

Proof of concept -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace EE_Q28963453
{
	class Program
	{
		static void Main(string[] args)
		{
			GetTransactionResponse response = new GetTransactionResponse()
			{
				Success = true,
				Transaction = new Transaction()
				{
					QuoteData = new QuoteData()
					{
						Attributes = new List<AttributeType>()
						{
							new AttributeType() { Field = "ProCesSinG_qUotE", Value = "1" },
							new AttributeType() { Field = "s_qUote", Value = "REGION5" },
							new AttributeType() { Field = "_qUotE_cOmpAny_nAme", Value = "ACME" },
							new AttributeType() { Field = "_emAIl", Value = "paul@acme.com" },
							new AttributeType() { Field = "prEparEdBy_quotE", Value = "Nancy" }
						},
						SubDocuments = new List<SubDocType>()
						{
							new SubDocType() { Attributes = new List<AttributeType>() { new AttributeType() { Field = "products", Value = "0**9**REG**03/29/2016**4**1$$2$$3$$4" }} },
							new SubDocType() { Attributes = new List<AttributeType>() { new AttributeType() { Field = "products", Value = "1**8**NOM****8**1$$2$$3$$4$$5$$6$$7$$8" }} },
							new SubDocType() { Attributes = new List<AttributeType>() { new AttributeType() { Field = "products", Value = "2**7**REG**05/29/2016**16**1$$2$$3$$4$$5$$6$$7$$8$$9$$10$$11$$12$$13$$14$$15$$16" }} },
							new SubDocType() { Attributes = new List<AttributeType>() { new AttributeType() { Field = "products", Value = "3**6**NOM**06/29/2016**8**1$$2$$3$$4$$5$$6$$7$$8" }} },
							new SubDocType() { Attributes = new List<AttributeType>() { new AttributeType() { Field = "products", Value = "4**5**REG****4**1$$2$$3$$4" }} }
						}
					}
				}
			};

			var request = response.ConvertToRequest();
			Console.WriteLine("Request for {0} at {1}", request.ContactEmailAddress, request.CompanyName);
			Console.WriteLine("From {0} in {1} by {2}", request.RegionalSalesOffice, request.RegionCode, request.DMName);
			foreach (var order in request.SalesOrders)
			{
				Console.WriteLine("Product Code: {0}; Sales Order Type: {1}; Start Date: {2}; Number Of Pays: {3}", order.ProductCode, order.SalesOrderType, order.StartDate, order.NumberOfPays);
				Console.WriteLine("ScnCodes: {0}", string.Join(" | ", (from code in order.ScnCodes select code.Code).ToArray()));
			}
			Console.ReadLine();
		}
	}

	static class Extensions
	{
		public static Request ConvertToRequest(this GetTransactionResponse response)
		{
			Request result = new Request();
			// Assuming that response is not null and successful
			if (response != null && response.Success)
			{
				var attributes = (from attribute in response.Transaction.QuoteData.Attributes
							   group attribute by attribute.Field into grp
							   let pair = grp.FirstOrDefault()
							   where pair != null && !string.IsNullOrWhiteSpace(pair.Value.ToString())
							   select new KeyValuePair<string, object>(pair.Field, pair.Value)).ToDictionary(k => k.Key, v => v.Value, StringComparer.OrdinalIgnoreCase);
				result.ApplyRequestAttributes(attributes);
				result.SalesOrders = (from document in response.Transaction.QuoteData.SubDocuments
								  let values = document.Attributes[0].Value.ToString().Split(new[] { "**" }, StringSplitOptions.None)
								  where (document.Attributes != null && document.Attributes.Count > 0) && !string.IsNullOrWhiteSpace(document.Attributes[0].Value.ToString()) && !string.IsNullOrEmpty(values[3])
								  select new SalesOrder()
								  {
									  ProductCode = values[1],
									  SalesOrderType = values[2],
									  StartDate = values[3],
									  NumberOfPays = !string.IsNullOrWhiteSpace(values[4]) ? int.Parse(values[4]) : 0,
									  ScnCodes = (from code in values[5].Split(new[] { "$$" }, StringSplitOptions.None) select new ScnCode() { Code = code }).ToList()
								  }).ToList();
			}
			return result;
		}

		private static void ApplyRequestAttributes(this Request request, Dictionary<string, object> attributes)
		{
			foreach (PropertyInfo property in request.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
			{
				FieldMappingAttribute[] mappings = (FieldMappingAttribute[])property.GetCustomAttributes(typeof(FieldMappingAttribute), false);
				if (mappings.Length > 0)
				{
					object value = null;
					foreach (var mapping in mappings)
					{
						if (attributes.TryGetValue(mapping.MapTo, out value))
						{
							property.SetValue(request, value, null);
							break;
						}
					}
				}
			}
		}
	}

	[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
	class FieldMappingAttribute : Attribute
	{
		public string MapTo { get; set; }
	}

	class GetTransactionResponse
	{
		public Transaction Transaction { get; set; }
		public bool Success { get; set; }
	}

	class Transaction
	{
		public QuoteData QuoteData { get; set; }
	}

	class QuoteData
	{
		public List<AttributeType> Attributes { get; set; }
		public List<SubDocType> SubDocuments { get; set; }
	}

	class SubDocType
	{
		public List<AttributeType> Attributes { get; set; }
	}

	class AttributeType
	{
		public string Field { get; set; }
		public object Value { get; set; }
	}

	class Request
	{
		[FieldMapping(MapTo = "processing_quote")]
		public string RegionCode { get; set; }
		[FieldMapping(MapTo = "salesoffice_quote"), FieldMapping(MapTo = "s_quote")]
		public string RegionalSalesOffice { get; set; }
		[FieldMapping(MapTo = "_quote_company_name")]
		public string CompanyName { get; set; }
		[FieldMapping(MapTo = "_email")]
		public string ContactEmailAddress { get; set; }
		[FieldMapping(MapTo = "preparedby_quote")]
		public string DMName { get; set; }
		public List<SalesOrder> SalesOrders { get; set; }
	}

	class SalesOrder
	{
		public string ProductCode { get; set; }
		public string SalesOrderType { get; set; }
		public string StartDate { get; set; }
		public int NumberOfPays { get; set; }
		public List<ScnCode> ScnCodes { get; set; }
	}

	class ScnCode
	{
		public string Code { get; set; }
	}
}

Open in new window

Produces the following output -Capture.JPG-saige-
0
 

Author Comment

by:Member_2_7967608
ID: 41759788
Thanks that works well. I had one more question sometimes values[5] has no data. It still creates the scn object.

Can we make scns = null when there is no data in values[5].

I basically want to ignore scns when I do serialization using Json.NET
0
 
LVL 34

Accepted Solution

by:
it_saige earned 2000 total points
ID: 41759822
Perhaps something like:
req.sOrders = (from document in resp.transaction.quote_data.sub_documents
			let values = document.attributes[0].value.ToString().Split(new[] { "**" }, StringSplitOptions.None)
			where (document.attributes != null && document.attributes.Length > 0) && !string.IsNullOrWhiteSpace(document.attributes[0].value.ToString()) && !string.IsNullOrEmpty(values[3])
			select new salesOrder()
			{
				productCode = values[1],
				salesOrderType = values[2],
				startDate = DateTime.Parse(values[3]).ToString("yyyy-MM-dd"),
				pays = !string.IsNullOrWhiteSpace(values[4]) ? int.Parse(values[4]) : 0,
				scns = !string.IsNullOrWhiteSpace(values[5]) ? (from code in values[5].Split(new[] { "$$" }, StringSplitOptions.RemoveEmptyEntries) select new scns() { scnCode = (String.IsNullOrEmpty(code) ? null : code) }).ToList() : null
			}).ToList();

Open in new window

Proof of concept -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace EE_Q28963453
{
	class Program
	{
		static void Main(string[] args)
		{
			GetTransactionResponse response = new GetTransactionResponse()
			{
				Success = true,
				Transaction = new Transaction()
				{
					QuoteData = new QuoteData()
					{
						Attributes = new List<AttributeType>()
						{
							new AttributeType() { Field = "ProCesSinG_qUotE", Value = "1" },
							new AttributeType() { Field = "s_qUote", Value = "REGION5" },
							new AttributeType() { Field = "_qUotE_cOmpAny_nAme", Value = "ACME" },
							new AttributeType() { Field = "_emAIl", Value = "paul@acme.com" },
							new AttributeType() { Field = "prEparEdBy_quotE", Value = "Nancy" }
						},
						SubDocuments = new List<SubDocType>()
						{
							new SubDocType() { Attributes = new List<AttributeType>() { new AttributeType() { Field = "products", Value = "0**9**REG**03/29/2016**4**" }} },
							new SubDocType() { Attributes = new List<AttributeType>() { new AttributeType() { Field = "products", Value = "1**8**NOM****8**1$$2$$3$$4$$5$$6$$7$$8" }} },
							new SubDocType() { Attributes = new List<AttributeType>() { new AttributeType() { Field = "products", Value = "2**7**REG**05/29/2016**16**1$$2$$3$$4$$5$$6$$7$$8$$9$$10$$11$$12$$13$$14$$15$$16" }} },
							new SubDocType() { Attributes = new List<AttributeType>() { new AttributeType() { Field = "products", Value = "3**6**NOM**06/29/2016**8**" }} },
							new SubDocType() { Attributes = new List<AttributeType>() { new AttributeType() { Field = "products", Value = "4**5**REG****4**1$$2$$3$$4" }} }
						}
					}
				}
			};

			var request = response.ConvertToRequest();
			Console.WriteLine("Request for {0} at {1}", request.ContactEmailAddress, request.CompanyName);
			Console.WriteLine("From {0} in {1} by {2}", request.RegionalSalesOffice, request.RegionCode, request.DMName);
			foreach (var order in request.SalesOrders)
			{
				Console.WriteLine("Product Code: {0}; Sales Order Type: {1}; Start Date: {2}; Number Of Pays: {3}", order.ProductCode, order.SalesOrderType, order.StartDate, order.NumberOfPays);
				Console.WriteLine("ScnCodes: {0}", order.ScnCodes != null ? string.Join(" | ", (from code in order.ScnCodes select code.Code).ToArray()) : "No SCN Codes");
			}
			Console.ReadLine();
		}
	}

	static class Extensions
	{
		public static Request ConvertToRequest(this GetTransactionResponse response)
		{
			Request result = new Request();
			// Assuming that response is not null and successful
			if (response != null && response.Success)
			{
				var attributes = (from attribute in response.Transaction.QuoteData.Attributes
							   group attribute by attribute.Field into grp
							   let pair = grp.FirstOrDefault()
							   where pair != null && !string.IsNullOrWhiteSpace(pair.Value.ToString())
							   select new KeyValuePair<string, object>(pair.Field, pair.Value)).ToDictionary(k => k.Key, v => v.Value, StringComparer.OrdinalIgnoreCase);
				result.ApplyRequestAttributes(attributes);
				result.SalesOrders = (from document in response.Transaction.QuoteData.SubDocuments
								  let values = document.Attributes[0].Value.ToString().Split(new[] { "**" }, StringSplitOptions.None)
								  where (document.Attributes != null && document.Attributes.Count > 0) && !string.IsNullOrWhiteSpace(document.Attributes[0].Value.ToString()) && !string.IsNullOrEmpty(values[3])
								  select new SalesOrder()
								  {
									  ProductCode = values[1],
									  SalesOrderType = values[2],
									  StartDate = values[3],
									  NumberOfPays = !string.IsNullOrWhiteSpace(values[4]) ? int.Parse(values[4]) : 0,
									  ScnCodes = !string.IsNullOrWhiteSpace(values[5]) ? (from code in values[5].Split(new[] { "$$" }, StringSplitOptions.None) select new ScnCode() { Code = code }).ToList() : null
								  }).ToList();
			}
			return result;
		}

		private static void ApplyRequestAttributes(this Request request, Dictionary<string, object> attributes)
		{
			foreach (PropertyInfo property in request.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
			{
				FieldMappingAttribute[] mappings = (FieldMappingAttribute[])property.GetCustomAttributes(typeof(FieldMappingAttribute), false);
				if (mappings.Length > 0)
				{
					object value = null;
					foreach (var mapping in mappings)
					{
						if (attributes.TryGetValue(mapping.MapTo, out value))
						{
							property.SetValue(request, value, null);
							break;
						}
					}
				}
			}
		}
	}

	[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
	class FieldMappingAttribute : Attribute
	{
		public string MapTo { get; set; }
	}

	class GetTransactionResponse
	{
		public Transaction Transaction { get; set; }
		public bool Success { get; set; }
	}

	class Transaction
	{
		public QuoteData QuoteData { get; set; }
	}

	class QuoteData
	{
		public List<AttributeType> Attributes { get; set; }
		public List<SubDocType> SubDocuments { get; set; }
	}

	class SubDocType
	{
		public List<AttributeType> Attributes { get; set; }
	}

	class AttributeType
	{
		public string Field { get; set; }
		public object Value { get; set; }
	}

	class Request
	{
		[FieldMapping(MapTo = "processing_quote")]
		public string RegionCode { get; set; }
		[FieldMapping(MapTo = "salesoffice_quote"), FieldMapping(MapTo = "s_quote")]
		public string RegionalSalesOffice { get; set; }
		[FieldMapping(MapTo = "_quote_company_name")]
		public string CompanyName { get; set; }
		[FieldMapping(MapTo = "_email")]
		public string ContactEmailAddress { get; set; }
		[FieldMapping(MapTo = "preparedby_quote")]
		public string DMName { get; set; }
		public List<SalesOrder> SalesOrders { get; set; }
	}

	class SalesOrder
	{
		public string ProductCode { get; set; }
		public string SalesOrderType { get; set; }
		public string StartDate { get; set; }
		public int NumberOfPays { get; set; }
		public List<ScnCode> ScnCodes { get; set; }
	}

	class ScnCode
	{
		public string Code { get; set; }
	}
}

Open in new window

Now produces the following output -Capture.JPG-saige-
0
Quick Start: DOCKER

Sometimes you just need a Quick Start on a topic in order to begin using it.. this is just what you need to know to get up and running with Docker!

 

Author Comment

by:Member_2_7967608
ID: 41759991
I did the change I get ScnCodes as count=0 .  I will need the value as null.
0
 
LVL 34

Expert Comment

by:it_saige
ID: 41760071
Verify that you have the ternary operator syntaxed properly and in the correct location.
Check that there is in fact nothing in values[5] (you may need to run a debug session for this)
Finally, ensure that you do not have anything else, anywhere creating a list of codes if the list in the object is null.

-saige-
0
 

Author Comment

by:Member_2_7967608
ID: 41760500
Thanks correct. There was one more condition in the terenary operator. This is resolved,

Thanks
0

Featured Post

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…
Suggested Courses

752 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question