Solved

Linq query filter List

Posted on 2016-08-15
6
72 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
  • 3
  • 3
6 Comments
 
LVL 33

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 33

Accepted Solution

by:
it_saige earned 500 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
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 

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 33

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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

839 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