Solved

Linq query filter List

Posted on 2016-08-15
6
56 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 32

Expert Comment

by:it_saige
Comment Utility
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
Comment Utility
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 32

Accepted Solution

by:
it_saige earned 500 total points
Comment Utility
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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:Member_2_7967608
Comment Utility
I did the change I get ScnCodes as count=0 .  I will need the value as null.
0
 
LVL 32

Expert Comment

by:it_saige
Comment Utility
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
Comment Utility
Thanks correct. There was one more condition in the terenary operator. This is resolved,

Thanks
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Converting C# Objects into JSON file 7 36
c# code 19 56
As soon as i click a button on the form,it mnimises. 11 19
Showdialog 8 20
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

772 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now