Index duplicates from the list using Linq - linq

Suppose I have a list of strings
var data = new List<string>{"fname", "phone", "lname", "home", "home", "company", "phone", "phone"};
I would like to list all values and add index to duplicates like this
fname,
phone,
lname,
home,
home[1],
company,
phone[1],
phone[2]
or like this
fname,
phone[0],
lname,
home[0],
home[1],
company,
phone[1],
phone[2]
The both solutions would work for me.
Is that possible with Linq?

You can use LINQ GroupBy to gather the matches, and then the counting version of Select to append the indexes.
var ans = data.GroupBy(d => d).SelectMany(dg => dg.Select((d, n) => n == 0 ? d : $"{d}[{n}]"));

Related

Is there a way to get all Contacts without specific criteria?

Using the Infusionsoft gem, is there a way to get all Contacts through the Infusionsoft API without a specific criteria?
Simply use the wildcard as a query parameter for the Id field:
query = {"Id" => "%"}
selected_fields = %w(Id FirstName LastName ...)
data = Infusionsoft.data_query("Contacts", 1000, 0 , query, selected_fields)
The API will return an array of hashes, each one representing the contact with the selected fields as keys.
As per yuga's comment, if you have more than 1000 contacts, you will need to add a loop for data pagination:
contacts = []
i = 0
query = {"Id" => "%"}
selected_fields = %w(Id FirstName LastName ...)
loop do
data = Infusionsoft.data_query("Contacts", 1000, i , query, selected_fields)
break if data.empty?
contacts.concat(data)
i += 1
end

Dynamic Linq Library can’t handling duplicate alias column names

I am trying to collect the data from database by using Dynamic Linq Library NeGet. When I loop through it showing this error ‘The item with identity 'FirstName' already exists in the metadata collection’
Seems like Dynamic Linq Library NuGet is can’t handle duplicate alias column names.
I have two tables and it has One-On-Many relationship as follow, containing the same Columns names in Lead table and CoBorrower table.
Table1: Lead
Columns: LeadID, FirstName,DateCreated
Table2: CoBorrower
Columns: LeadID, CoBorrowerID,FirstName,Tax,DateCreated
Here is my code snippet
var res = (from l in db.Leads
join db.CoBorrower.GetAll()
on l.LeadID equals cb.LeadID
select new { l, cb }).AsQueryable();
string myCustomCondition="FistName=myname";
IQueryable iq = res.Where(myCustomCondition)
.OrderBy(reportBulder.Group1)
.Select("new(l.LeadID,l.FirstName,cb.FistName)")
.GroupBy("LeadID", "it")
.Select("new (it.Key as Key, it as Value)");
foreach (dynamic group in iq)
{
string Key = group.Key.ToString();
List<dynamic> items = new List<dynamic>();
foreach (dynamic album in group.Value)
{
items.Add(album);
}
dataList.Add(Key, items);
}
I will appreciate your help in advance.
This is logical. The .Select("new(l.LeadID,l.FirstName,cb.FistName)") will create an anonymous object like:
new
{
LeadID = ....,
FirstName = ....,
FirstName = ....,
}
that is illegal (two properties with the same name)
Use the as
.Select("new(l.LeadID,l.FirstName,cb.FistName as FirstName2)")
so that the anonymous object created is
new
{
LeadID = ....,
FirstName = ....,
FirstName2 = ....,
}
as you do in the second .Select.

how to use a dynamic variable in orderby clause

am a newbie in linq.. am stuck with one scenario. ie,
i have to sort the search results based on user input.
user inputs are Last Name, First Name and Title. for input 3 drop downs are there and i have to sort result based on the values selected.
i tried
order = Request["orders"].Split(',');
var param = order[0];
var p1 = typeof(Test).GetProperty(param);
param = order[1];
var p2 = typeof(Test).GetProperty(param);
param = order[2];
var p3 = typeof(Test).GetProperty(param);
model.Test = (from tests in model.Test
select tests).
OrderBy(x => p1.GetValue(x, null)).
ThenBy(x => p2.GetValue(x, null)).
ThenBy(x => p3.GetValue(x, null));
but it doesn't works.
i want qry like this
from tests in model.Test
select tests).OrderBy(x => x.lastname).
ThenBy(x => x.firstname).ThenBy(x => x.Title);
order[0]== lastname but how can i use it in the place of OrderBy(x => x.order[0])..?
Thanks in advance.
i solved my case as follows
// list of columns to be used for sorting
List<string>order = Request["orders"].Split(',').ToList();
//map the column string to property
var mapp = new Dictionary<string, Func<Test, string>>
{
{"FirstName", x => x.FirstName},
{"LastName", x => x.LastName},
{"SimpleTitle", x => x.SimpleTitle}
};
//user inputted order
var paras = new List<Func<Test, string>>();
foreach (var para in order)
{
if(!string.IsNullOrEmpty(para))
paras.Add(mapp[para]);
}
//sorting
model.Test= model.Test.OrderBy(paras[0]).ThenBy(paras[1]).ThenBy(paras[2]);
Thanks all,
Actually you are looking for dynamic linq query than you can try out Dynamic LINQ (Part 1: Using the LINQ Dynamic Query Library)
which allow to do like this
it means you can dynamically pass string propertyname to short you collection in orderby function
You can also read about : Dynamic query with Linq
You can compose the expression (any Expression) manually from pieces and then append it to the previous part of query. You can find more info, with example in "Sorting in IQueryable using string as column name".

LINQ create multiple new entities using a single ID field

I have a newbie LINQ question. I need to create two objects of same type from a list of strings. I need to append a text 'Direct' & "Indirect' to the string and use them as ID to create the two unique objects.
var vStrings = new List { "Milk", "Eggs", "Cheese" };
var vProducts = (from s in vStrings
select new Product { ID = s + "-Direct" })
.Union(
from s in vStrings
select new Product { ID = s + "-InDirect" });
You can see in the example above, I am using a Union to create two different objects, Is there a better way to rewrite this LINQ query?
Thanks for your suggestions
If you ever needed more suffixes, this might be a better way:
var strings = new List<string> { "Milk", "Eggs", "Cheese" };
var suffixes = new List<string> {"-Direct", "-InDirect"};
var products = strings
.SelectMany(_ => suffixes, (x, y) => new Product() {ID = x + y});
And it would only iterate over the original set of strings once.
This way isn't much shorter but I think it would be a little better such as there is only one Concat instead of many Union:
var vProducts2 = (from s in vStrings
select s + "-Direct").Concat(
from s in vStrings
select s + "-InDirect");

how to insert an array of id's into linq-to-sql query line in .net mvc 3

i want to get an array of id's which is like ["15", "26", "37", "48", "90"] and i want to get my remaining items from my remaining table that doesnt includes these supplier id's..
here what i done so far:
string[] arrgroupdetails;
arrgroupdetails = dataContext.GroupDetails.Select(c => c.supplier_id).ToArray();
var items = from thingies in dataContext.remainings where thingies.supplier_id.ToString() != arrgroupdetails.Any().ToString() select thingies;
so how can i achive this?
By heart, so do check syntax but someething like this should work:
var items = from thingies in dataContext.remainings
where !arrgroupdetails.Contains(thingies.supplier_id.ToString())
select thingies;

Resources